2017-10-20 1 views
0

내 프로젝트에서 Ninject lib 사용하고 있습니다. 나는 과제가있다 : 전달 된 사전에 의해 인터페이스를 서비스에 바인딩 할 필요가있다. 나는 리플렉션을 선호한다.C# Ninject 바인딩에서 사전

반사없이이 그렇게되어

kernel.Bind<IUser>().To<User>(); 

경우 IUSER - 인터페이스, 사용자 - IUSER 구현을.

MethodInfo method = kernel.GetType().GetMethods().FirstOrDefault(x=>x.Name == "Bind"); 
MethodInfo genericBind = method.MakeGenericMethod(bind.Key); 
MethodInfo bindResult = genericBind.Invoke(kernel,null).GetType().GetMethods().FirstOrDefault(x => x.Name == "To" && x.IsGenericMethod == true); 
MethodInfo genericTo = bindResult.MakeGenericMethod(bind.Value); 
genericTo.Invoke(kernel, null); //Error is here 

하지만 오류 System.Reflection.TargetException를 얻을 : 반사에서

는 내가 그렇게.

무엇이 잘못 되었나요?

+0

4 개 라인의 어떤 오류 메시지를 표시 할 수 있습니까? –

+0

마지막 하나. 하지만 나는 정확히 shure, 그 bind.Value는 bind에서 구현됩니다 .Key ... –

+0

제 생각에는 bindResult를 호출해야합니다. –

답변

0

확인 문제 :-) 내 영어 죄송합니다

는 커널 객체가 아니라 방법의 결과에 메소드를 호출하는 것입니다. 이 문제가 해결됩니다

MethodInfo method = kernel.GetType().GetMethods().FirstOrDefault(x=>x.Name == "Bind"); 
MethodInfo genericBind = method.MakeGenericMethod(bind.Key); 
var result = genericBind.Invoke(kernel,null); 
MethodInfo bindResult = result.GetType().GetMethods().FirstOrDefault(x => x.Name == "To" && x.IsGenericMethod == true); 
MethodInfo genericTo = bindResult.MakeGenericMethod(bind.Value); 
genericTo.Invoke(result, null); //Error is here 

하지만이 모든 바인딩 기능이 아닌 일반적인 구현 kernel.Bind(typeof(IUser)).To(typeof(User))이 있기 때문에 불필요 그래서 그냥 kernel.Bind(bind.Key).To(bind.Value)