如何通过使用依赖注入
问题描述:
一个参数的DbContext构造我返工我的DbContext通过要求tenantId支持多租户的中间是:如何通过使用依赖注入
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;
}
我使用的是统一的,但还没有真的完成了很多配置 - 这一切都正常。
我将从我的控制器中检索tenantId
。我如何去从Controller> Service layer>构造函数传递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;
}
这是它的一个实例。
您应该注入'DbContextFactory',并创建一个像'factory.CreateDbContextForTenant(int tenantId)'这样的方法。 –