[英]How to pass a type as parameter to a constructor when using Unity dependency injection
[英]How to pass a parameter to DbContext constructor using Dependency Injection
我正在通過要求一個tenantId來重做DbContext以支持多租戶的過程:
public AppContext(int tenantId)
{
_tenantId = tenantId;
}
以前,沒有參數。
在我的服務類中,我用DI實例化了上下文:
private readonly AppContext db;
private CommService _commService;
public AdminService(AppContext db, CommService commService)
{
this.db = db;
_commService = commService;
}
在我的控制器中,同樣的事情:
private readonly CommService _commService;
public AdminController(CommService commService) {
_commService = commService;
}
我正在使用Unity,但實際上並沒有做太多配置-一切都正常。
我將從控制器中檢索tenantId
。 我該如何從Controller> Service layer> Constructor傳遞tenantId?
Unity無法傳遞tenantId
因為這是一個變量,例如,這將取決於當前使用情況或任何其他條件, tenantId
將在運行時確定,因此不要使其可注入。
不過,您可以為其建立工廠並增加該工廠的數量。
例如:
public Interface ITenantDiscovery
{
int TenantId{get;}
}
public class UrlTenantDiscovery:ITenantDiscovery
{
public int TenantId
{
get
{
var url = -- get current URL, ex: from HttpContext
var tenant = _context.Tenants.Where(a=>a.Url == url);
return tenant.Id; -- cache the Id for subsequent calls
}
}
在UnityConfig中,注冊ITenantDiscovery
及其實現UrlTenantDiscovery
更改您的AppContext以接受ITenantDiscovery
的實例
public AppContext(ITenantDiscovery tenantDiscovery)
{
_tenantId = tenantDiscovery.TenantId;
}
這就對了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.