Autofac Multi-Tenant ASP.NET Application return 租户而不是标识符

Autofac Multi-Tenant ASP.NET Application return the tenant instead of the identifier

我正在使用 Autofac 作为 IoC 容器,带有 Autofac.Multitenant 多租户包。

我有一个这样的容器设置:

var builder = new ContainerBuilder();

// Register the controllers    
builder.RegisterControllers(typeof(Deskful.Web.DeskfulApplication).Assembly);

// Tenant Identifier
var tenantIdentifier = new RequestSubdomainStrategy();

builder.RegisterInstance(tenantIdentifier).As<ITenantIdentificationStrategy>();

// Build container
var container = builder.Build();

// Tenant container
var mtc = new MultitenantContainer(tenantIdentifier, container);

// Set autofac as dependency resolver
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

以及我的识别策略:

public class RequestSubdomainStrategy : ITenantIdentificationStrategy
{
    public bool TryIdentifyTenant(out object tenantId)
    {
        tenantId = null;

        try
        {
            var context = HttpContext.Current;
            if (context != null && context.Request != null)
            {
                var site = context.Request.Url.Host;

                tenantId = 1;
            }
        }
        catch { }

        return tenantId != null;
    }
}

然后在我需要租户的控制器中,我可以在注入 ITenantIdentificationStrategy 后执行以下操作:

var tenantId = this.TenantIdStrategy.IdentifyTenant<int>();

我的问题是,如何在识别过程中存储租户对象,以便我可以访问租户的所有属性?

因为现在只有 returns id。

不知道这是否是正确的解决方案,但我最终执行了以下操作。

首先我创建了一个新接口来扩展当前的 ITenantIdentificationStrategy:

public interface IDeskfulTenantIdentificationStrategy : ITenantIdentificationStrategy
{
    ITenant Tenant { get; }
}

我扩展了与租户的接口属性。

然后在我的标识符class中,我在识别过程中设置租户属性:

public class RequestSubdomainStrategy : IDeskfulTenantIdentificationStrategy
{
    private ITenant _tenant;

    public ITenant Tenant
    {
        get
        {
            return _tenant;
        }
        private set
        {
            _tenant = value;
        }
    }

    public bool TryIdentifyTenant(out object tenantId)
    {
        tenantId = null;

        try
        {
            var context = HttpContext.Current;
            if (context != null && context.Request != null)
            {
                var site = context.Request.Url.Host;

                Tenant = new Tenant("tenant1.deskfull.be", "connString", "Tenant 1") { Id = 20 };

                tenantId = Tenant.Id;
            }
        }
        catch { }

        return tenantId != null;
    }
}

最后我在我的 autofac 容器中注册了新的接口:

var tenantIdentifier = new RequestSubdomainStrategy();

builder.RegisterInstance(tenantIdentifier)
.As<IDeskfulTenantIdentificationStrategy>();

当我在控制器中使用它时,我可以执行以下操作:

public string Index()
{
    int tenantId = TenantIdStrategy.IdentifyTenant<int>();

    return "Home - Index: " + TenantIdStrategy.Tenant.TenantName;
}