2013-04-16 4 views
5

승 결합 제가 TEntity 파생 경우가 T에 기초하여 바인딩 구체적 xrmRepository를 사용하여 변경할 범용 인터페이스를 IRepository<T> 두 구현 xrmRepository<T>efRepository<T>Ninject에 문맥/오픈 제네릭

있다. 어떻게해야합니까?

내가 현재 가지고 :

kernel.Bind(typeof(IRepository<>)).To(typeof(efRepository<>)).InRequestScope(); 
kernel.Bind(typeof(IRepository<>)).To(typeof(xrmRepository<>)).When(request => request.Service.GetGenericArguments()[0].GetType().IsSubclassOf(typeof(Entity))).InRequestScope(); 

을하지만 IRepository<Contact>를 해결하려고 할 때이 연락이 엔티티를 상속하더라도, efRepository로 이동합니다.

명명 된 바인딩을 사용하고 싶지 않다면 어디에서나 이름을 추가해야합니다.

답변

2

이와 같은 바인딩을 정의 할 수도 있습니다. 런타임 성능에 대해서는 잘 모르겠지만이 방법이 더 읽기 쉽다고 생각합니다. 그리고 만약 내가 뭔가를 놓치지 않는다면 같은 행동을하게 될 것입니다.

kernel.Bind(typeof(IRepository<>)) 
     .To(typeof(efRepository<>)) 
     .InRequestScope(); 

kernel.Bind<IRepository<Entity>>() 
     .To<xrmRepository<Entity>>() 
     .InRequestScope(); 

편집

목표는 점점이 트릭을

kernel.Bind(typeof(IRepository<>)) 
        .To(typeof(XrmRepository<>)) 
        .When(request => typeof(Entity).IsAssignableFrom(request.Service.GetGenericArguments()[0])); 
+0

"Entity"기본 클래스를 사용하여 작동하지 않았습니다. 아직도 efRepository에 바인딩. 클래스 자체 (예 : 연락처)를 사용하는 경우 작동합니다. –

+0

Entity의 모든 하위 클래스에 대해 IRepository를 xrmRepository로 해결 하시겠습니까? – treze

+0

예! 그러나 아마도 IXRMRepository를 만들게 될 것입니다. IRepository는 작동하지 않을 수 있기 때문에 대신에 사용합니다. –

1

When 메서드를 사용하여 바인딩 조건을 선언하십시오. 예제는 다음과 같습니다.

kernel.Bind(typeof(IRepository<>)) 
     .To(typeof(efRepository<>)) 
     .When(request => request.Service.GetGenericArguments()[0] == typeof(Entity)) 
     .InRequestScope(); 

kernel.Bind(typeof(IRepository<>)) 
     .To(typeof(xrmRepository<>)) 
     .InRequestScope(); 

kernel.Get<IRepository<Entity>>(); //will return efRepository<Entity> 

kernel.Get<IRepository<int>>(); //will return xrmRepository<int> 
+0

보관할을해야 엔터티에서 상속하는 모든 클래스에 대한 xrmRepository를 사용하는 경우 오류 "GenericArguments [0], 'sf2015 .Infrastructure.Xrm.Contact ', on'sf2015.Repositories.sfRepository'1 [T] '이 (가) 매개 변수'T '유형의 제약 조건을 위반합니다. " 추가 정보 : f2015.Infrastructure.Xrm.Contact는 Microsoft.Xrm.Sdk.Entity 유형입니다. 먼저 First()를 [0]으로 변경하고 xrmRepository를 Entity와 바인딩해야합니다. 업데이트 된 질문보기 –

+0

@ JoaoLeme는 인터페이스 정의와 구현을 제공합니다. 또한 ** Get ** 및 예상 결과를 호출하는 예제를 제공하십시오 –

+0

새 모듈에서 Get을 호출하면 GetGenericArguments()를 사용하면 작동합니다. First() == typeof (Contact) ... 및 kernel.Get >(); 하지만 바인딩에 대한 연락처를 상속받은 클래스 Entity로 대체하고 kernel.Get >()을 호출하면 같은 오류가 발생합니다. 그런데 NinjectWebCommon의 RegisterServices에서 동일한 문제 해결 트릭을 수행 (Entity by Contact)하면 작동하지 않습니다 (Eitherway는 저에게 같은 오류를줍니다). –