2017-10-20 56 views
0

我在我的項目中使用Ninject lib。我有一個任務:我需要通過傳遞的字典將接口綁定到服務,我更喜歡使用反射。C#Ninject綁定從字典<Type, Type>

沒有反射,這是這樣做的:

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

最後一個。但我確切地說,那個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)),所以你可以做 ​​3210