C#Ninject从Dictionary <type,type =“”>绑定

时间:2017-10-20 04:50:52

标签: c# asp.net api web ninject

我在我的项目中使用Ninject lib。我有一个任务:我需要通过传递字典将接口绑定到服务,我更喜欢使用反射。

如果没有反思,就这样做了:

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

IUser - interface,User - IUser implementation。

在反思中我这样做:

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。

有什么问题?

对不起我的英文:-)

1 个答案:

答案 0 :(得分: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

但是这一切都是不必要的,因为Bind函数有一个非通用的实现kernel.Bind(typeof(IUser)).To(typeof(User)),所以你可以做 kernel.Bind(bind.Key).To(bind.Value)