[英]How to pass a parameter to DbContext constructor using Dependency Injection
I'm in the middle of reworking my DbContext to support Multitenancy by requiring a tenantId: 我正在通过要求一个tenantId来重做DbContext以支持多租户的过程:
public AppContext(int tenantId)
{
_tenantId = tenantId;
}
Before, there was no parameter. 以前,没有参数。
In my service classes, I have the context instantiated with DI: 在我的服务类中,我用DI实例化了上下文:
private readonly AppContext db;
private CommService _commService;
public AdminService(AppContext db, CommService commService)
{
this.db = db;
_commService = commService;
}
And in my Controllers, the same thing: 在我的控制器中,同样的事情:
private readonly CommService _commService;
public AdminController(CommService commService) {
_commService = commService;
}
I'm using Unity, but haven't really done much configuration at all - it all just works. 我正在使用Unity,但实际上并没有做太多配置-一切都正常。
I'll be retrieving the tenantId
from my Controllers. 我将从控制器中检索
tenantId
。 How do I go about passing the tenantId from Controller > Service layer > Constructor? 我该如何从Controller> Service layer> Constructor传递tenantId?
Unity can't pass the tenantId
as this is a variable which will depend on the current use for example or any other condition, the tenantId
will be determined at runtime, so don't make it injectable. Unity无法传递
tenantId
因为这是一个变量,例如,这将取决于当前使用情况或任何其他条件, tenantId
将在运行时确定,因此不要使其可注入。
Still, you can make a factory for it and injecet this factory. 不过,您可以为其建立工厂并增加该工厂的数量。
ex: 例如:
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
}
}
In UnityConfig, register the ITenantDiscovery
and its implementation UrlTenantDiscovery
在UnityConfig中,注册
ITenantDiscovery
及其实现UrlTenantDiscovery
Change your AppContext to accept an instance of ITenantDiscovery
更改您的AppContext以接受
ITenantDiscovery
的实例
public AppContext(ITenantDiscovery tenantDiscovery)
{
_tenantId = tenantDiscovery.TenantId;
}
That is it. 这就对了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.