Skip to main content
All docs
V24.2

Get the Current Tenant in Code

  • 2 minutes to read

Code-Based (Programmatically)

To get the current tenant ID and/or name in application code, use the ITenantProvider service. You can use one of the following techniques to access this service:

  • Use the application’s Service Provider (available through Application.ServiceProvider, ObjectSpace.ServiceProvider, and so on).

    using DevExpress.ExpressApp.MultiTenancy;
    // ...
    var tenantProvider = ObjectSpace.ServiceProvider.GetService<ITenantProvider>(); 
    Guid? currentTenantId = tenantProvider.TenantId;  
    string currentTenantName = tenantProvider.TenantName; 
    Tenant tenant = (Tenant)tenantProvider.TenantObject;
    
  • Use Dependency Injection in constructors of controllers or custom services registered in the application.

    using DevExpress.ExpressApp;
    using DevExpress.ExpressApp.MultiTenancy;
    // ...
    public class MyViewController : ViewController {
        ITenantProvider tenantProvider;
        // ...
        [ActivatorUtilitiesConstructor]
        public MyViewController(IServiceProvider serviceProvider) : base() {
            // ...
            tenantProvider = serviceProvider.GetService<ITenantProvider>();
        }
        protected override void OnActivated() {
            base.OnActivated();
            Guid? currentTenantId = tenantProvider.TenantId;
            string currentTenantName = tenantProvider.TenantName;
            Tenant tenant = (Tenant)tenantProvider.TenantObject;
            // ...
        }
    }
    

The ITenantProvider interface exposes the ITenantProvider.TenantId and ITenantProvider.TenantName properties, which return the current tenant’s unique identifier and name respectively if a user is currently logged in to the Tenant User Interface. If a user is not currently logged in or the Host User Interface is used, these properties return null.

The ITenantProvider.TenantObject property returns the tenant object, which you can use to access the tenant data directly. Use this property to access additional fields of a custom tenant. For more information, refer to Extend the Built-in Tenant Class with Custom Fields. If a user is not currently logged in or the Host User Interface is used, this property returns null.

Criteria-Based (Filtering)

In a criteria operator expression, you can use the CurrentTenantId function to get the current tenant:

var criteria = CriteriaOperator.FromLambda<BusinessObject>(
    x => x.TenantId == (Guid?)CurrentTenantIdOperator.CurrentTenantId()
);

This function returns the tenant ID if a user is logged in to the Tenant User Interface. If a user is not logged in or the Host User Interface is used, the function returns null.

See Also