0

를 사용 DbContext의 생성자에 매개 변수 전달하는 방법 : 전에내가 tenantId을 요구하여 다중 테넌트를 지원하기 위해 내 DbContext 재 작업의 중간에있어 의존성 삽입 (Dependency Injection)

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을 가져오고 있습니다. 컨트롤러> 서비스 레이어> 생성자에서 임차인을 전달하려면 어떻게해야합니까?

+0

대신'DbContextFactory'를 삽입하고'factory.CreateDbContextForTenant (int tenantId)'와 같은 메소드를 생성해야합니다. –

답변

0

Unity는 tenantId을 전달할 수 없습니다. 예를 들어 현재 상태 또는 다른 조건에 따라 달라지는 변수이므로 tenantId은 런타임에 결정되므로 주사 할 수 없습니다.

여전히 공장을 만들고이 공장에 주사 할 수 있습니다.

예 : UnityConfig에서

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 
    } 
} 

는, 그것을이다 ITenantDiscovery

public AppContext(ITenantDiscovery tenantDiscovery)    
    { 
     _tenantId = tenantDiscovery.TenantId; 
    } 

의 인스턴스를 허용하도록 ITenantDiscovery 및 구현 UrlTenantDiscovery

변경에게 AppContext를 등록합니다.