2016-07-24 4 views
1

두 개의 개별 리포지토리 클래스를 만들기 위해 DI 다음에 가장 좋은 방법은 무엇입니까?생성자 삽입 - 두 개의 개별 구성 종속성을 리포지토리 클래스에 바인딩

public class FirstDbRepo : Repository 

public class SecondDbRepo : Repository 
기본적으로

namespace MyApp.Persistence 
{ 
    public class Repository<T> : IRepository<T> where T : EntityBase 
    { 
     public IConfig Config { get; set; } 
     private Database Database 
     { 
      get 
      { 
       // Use Config to get connection 
      }; 
      set; 
     } 

     public Repository(IConfig config) 
     { 
      Config = config; 
     } 

     public IEnumerable<T> Get(Expression<Func<T, bool>> predicate) 
     { 
      // Use database to get items 
     } 

     public T CreateItem(T item) 
     { 
      // Use database to create item 
     } 
    } 
} 

아래의 저장소를 구현하지만 다른 설정 값/인스턴스를 주입하는

...

public interface IConfig 
{ 
    string DatabaseName{ get; } 
    string DatabaseEndpoint{ get; } 
    string DatabaseAuthKey{ get; } 
} 

내가 생각하는 첫번째 일은 마커를 만드는 것이 었습니다 인터페이스가 있지만이 냄새가 나는지 알고 싶습니다 ... DI를 사용하여이 작업을 수행하는 올바른 방법이 있습니까?

public interface IFirstDbRepo { } 

public class FirstDbRepo<T> : Repository<T> where T: EntityBase 
{ 
    public FirstDbRepo(FirstConfig config) 
     : base(config) 
    { } 
} 

public class FirstConfig : IConfig 
{ 
    public string DatabaseName{ get { return "MyName" }; } // From web.config 
} 

그리고 각각의 repo에 대한 바인딩해서 Ninject를 사용 ...로 사용할 수있는 소비자는

public class Consumer() { 
    private readonly IFirstDbRepo _firstRepo; 
    public Consumer(IFirstDbRepo firstRepo) { 
     _firstRepo = firstRepo; 
    } 
} 
+0

귀하의'Consumer' 클래스는 콘크리트에 대한 종속성이 다음 클래스'FirstDbRepo' 그래도? 이상적으로 당신의'T'는 둘 사이에서 분리 될 것입니다. 그러면 당신은'T'의 타입에 기초하여 어떤 구현을 나눌 수 있습니다. 그렇지 않으면 나는 여기에서 Factory 패턴을 롤백 할 것입니다. 그러나 그것보다 좋은 방법이있을 수 있습니다 : P – starlight54

+0

문맥 바인딩을 고소하지 않으려면 마커 인터페이스를 사용하는 것이 좋습니다. –

답변

1
Bind<IConfig>().To<MyConfigOne>().WhenInjectedInto(typeof(FirstDbRepo)); 
Bind<IConfig>().To<MyConfigTwo>().WhenInjectedInto(typeof(SecondDbRepo)); 

Contextual binding