如何使用依赖注入将参数传递给 DbContext 构造函数

How to pass a parameter to DbContext constructor using Dependency Injection

我正在修改我的 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;
    }

我正在使用 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;
    }

就是这样。