![](/img/trans.png)
[英]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.