2015-01-29 3 views
0

MongoCollection을 내 저장소 레이어에 삽입하려고합니다. 즉 무엇을해야Generic과 Mongo로 Ninject 바인딩

Func<Type, string> namingStrategy = x => x.Name; 
      Kernel.Bind(typeof(MongoCollection<>)) 
      .ToMethod(
       x => x.Kernel.Get<MongoDatabase>().GetCollection(x.Request.Target.Type, namingStrategy(x.Request.Target.Type))); 

, 그것은에 대한 모든 MongoCollection <가> 우리 MongoDatabase 개체에서 컬렉션 개체를 얻어서 구현의 바인드됩니다. 이 "좀"작동하지만이 오류 얻을 :

Unable to cast object of type 'MongoDB.Driver.MongoCollection`1[MongoDB.Driver.MongoCollection`1[Profile]]' to type 'MongoDB.Driver.MongoCollection`1[Profile] 

공지가에서 캐스팅 것 유형 더블 generic'd입니다. 예 :

MongoCollection<MongoCollection<Profile>> 

필자가 작성한 코드에서 어떻게 벗어나고 있는지 확신 할 수 없습니다. 오류를 자세히 보면,의

답변

2

첫째, 당신이

MongoCollection<Profile> 

에 캐스트 할 수없는 유형

MongoCollection<MongoCollection<Profile>> 

의 객체 (인스턴스)를 가지고 있음을 말한다 이것은 요청에 문제가 아니며 ninject가 MongoCollection<Profile>을 원하고 ToMethod의 결과를이 유형으로 캐스팅하려고하기 때문에 ninject와 관련된 문제가 아니라는 것을 보여줍니다. 그러나 ToMethod에 전달한 Func은 MongoCollection<MongoCollection<Profile>>을 반환합니다. 하지만 왜?

x.Request.Target.Type 

MongoCollection<Profile>! 이제 MongoDatabase.GetCollectionProfile이 전달 될 것으로 예상되므로 잘못된 것입니다. 그래서 당신이 할 수있어 한 것은 사용하는 것입니다 : 대신

x.Request.Target.Type 
    .GetGenericArguments() 
    .Single(); 

. Profile을 반환합니다.

관련 문제