gpt4 book ai didi

c# - Ninject 从 IBinding 获取目标类型

转载 作者:太空狗 更新时间:2023-10-29 22:14:28 24 4
gpt4 key购买 nike

我有一个由多种类型实现的接口(interface)。但在我做 kernel.GetAll<IAmServiceable>() 之前我希望能够思考注入(inject)的目标类型。

我知道函数 kernel.GetBindings(typeof(IAmServiceable))存在,但这会返回 IBinding 的列表的。

有谁知道如何从 IBinding 中获取目标类型?

我想知道绑定(bind)到 IAmServiceable 的类型在它被实例化之前。

最佳答案

我知道现在解决你的问题可能有点晚了,但自从我今天遇到这个问题后,我想其他人也可能遇到。

这是我最终想出的代码——我认为它并不完美(远非完美),尤其是在性能方面,但它适用于我的情况,而且由于我不打算经常调用此方法,它我觉得没问题。

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));
}

关于c# - Ninject 从 IBinding 获取目标类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10243047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com