【发布时间】:2015-12-17 14:00:20
【问题描述】:
我正在使用 ASP.NET 5 和 EF7 编写多租户 Web 服务。存储库数据特定于租户/用户。因为我将在所有调用中使用 TenantId,所以我想用当前的 TenantId 初始化存储库。
public class MyRepository {
private int tenantId;
public MyRepository(MyDbContext context, int tenantId) {
this.tenantId = tenantId;
// ...
}
public Task<List<Data>> GetAllAsync() {
return this.context.Data.Where(d => d.TenantId == this.tenantId).ToListAsync();
}
}
public class Startup {
public void ConfigureServices(IServiceCollection services) {
// How do I pass the TenantId to the constructor?
services.AddScoped<MyRepository>();
}
}
是否可以在用户通过身份验证后初始化我的存储库一次?如何通过构造函数传递 TenantId?
【问题讨论】:
-
你可以注入一个只包含租户ID的接口并使用
AddInstance方法,像这样:services.AddInstance<ITenant>(GetTenantMethod());甚至services.AddScoped<ITenant>(x => GetTenantMethod());
标签: asp.net-mvc dependency-injection asp.net-core asp.net-core-mvc entity-framework-core