alb*_*jan 5 c# dependency-injection ninject inversion-of-control
我有一个由几种类型实现的接口.但在我做之前,我kernel.GetAll<IAmServiceable>()希望能够思考注射的目标类型.
我知道函数kernel.GetBindings(typeof(IAmServiceable))存在,但这会返回一个列表IBinding.
有谁知道如何从中获取目标类型IBinding?
我想知道在IAmServiceable实例化之前绑定的类型.
Sch*_*der 11
我知道你的问题现在可能有点晚了,但是因为我今天遇到了这个问题,我认为其他人也可能.
这是我最终提出的代码 - 我认为它不完美(远离它),特别是关于性能,但它适用于我的情况,因为我不打算经常调用这种方法,似乎没关系我.
public Type GetBoundToType(IKernel kernel, Type boundType)
{
var binding = kernel.GetBindings(boundType).FirstOrDefault();
if (binding != null)
{
if (binding.Target != BindingTarget.Type && binding.Target != BindingTarget.Self)
{
// TODO: maybe the code below could work for other BindingTarget values, too, feelfree to try
throw new InvalidOperationException(string.Format("Cannot find the type to which {0} is bound to, because it is bound using a method, provider or constant ", boundType));
}
var req = kernel.CreateRequest(boundType, metadata => true, new IParameter[0], true, false);
var cache = kernel.Components.Get<ICache>();
var planner = kernel.Components.Get<IPlanner>();
var pipeline = kernel.Components.Get<IPipeline>();
var provider = binding.GetProvider(new Context(kernel, req, binding, cache, planner, pipeline));
return provider.Type;
}
if (boundType.IsClass && !boundType.IsAbstract)
{
return boundType;
}
throw new InvalidOperationException(string.Format("Cannot find the type to which {0} is bound to", boundType));
}
Run Code Online (Sandbox Code Playgroud)
这不可能。例如,本例中的类型是什么?
Bind<IX>().ToMethod(c => RandomBool() ? new Foo() : new Bar());
Run Code Online (Sandbox Code Playgroud)