2017-06-28 41 views
0

我正在使用Autofac作爲IoC容器和Autofac.Multitenant包,用於多租戶。Autofac Multi-Tenant ASP.NET應用程序返回租戶而不是標識符

我有一個容器的設置是這樣的:

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>(); 

我的問題是,如何存儲租戶對象d通過我的身份識別過程,我可以訪問租戶的所有屬性?

因爲現在它只返回id。

回答

0

不知道這是否是一個正確的解決方案,但我最終做了以下事情。

首先我創建了一個新的接口來擴展當前ITenantIdentificationStrategy

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

我擴展了承租人財產的接口。

然後在我的標識符I類鑑定過程中設置的租戶屬性:

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; 
    } 
} 

最後我註冊新inteface在我autofac容器:

var tenantIdentifier = new RequestSubdomainStrategy(); 

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

當我再使用這裏面我控制器,我可以做到以下幾點:

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

    return "Home - Index: " + TenantIdStrategy.Tenant.TenantName; 
} 
相關問題