gpt4 book ai didi

ninject - 如何迭代 Ninject StandardKernel 的已配置绑定(bind)以进行调试?

转载 作者:行者123 更新时间:2023-12-04 16:11:07 24 4
gpt4 key购买 nike

在我的 Ninject 绑定(bind)模块中,

public class CarModule : NinjectModule 
{
public override void Load()
{
Kernel.Bind(scanner => scanner.FromThisAssembly().SelectAllClasses()
.InheritedFrom<ICar>().BindAllInterfaces());

foreach (var binding in kernel.GetBindings(typeof(ICar)))
{
Trace.WriteLine(string.Format("[{0}] Service bound to [{1}]",
binding.Service.Name,
binding.Target.GetType().Name));
}

// Output looks like:
//[ICar] Service bound to [BindingTarget]
//[ICar] Service bound to [BindingTarget]
//[ICar] Service bound to [BindingTarget]
}
}

我需要进行健全性检查以查看已成功绑定(bind)到我的服务的类型。我无法访问 绑定(bind)类型的类型名称 .而不是 [BindingTarget] , 我想看看 [Mercedes] , [Ferrari] , ETC...

有没有好的和/或常见的方法来做到这一点?

最佳答案

在您的 IocKernel 中,我只需添加一个方法来获取给定类型 T 的所有实例,并在加载您的模块后调用它:

    public static class IocKernel
{
private static StandardKernel _kernel;

public static IEnumerable<T> GetAll<T>()
{
return _kernel.GetAll<T>();
}

public static void Initialize(params INinjectModule[] modules)
{
if (_kernel == null)
{
_kernel = new StandardKernel(modules);

List<ICar> bindingsList= _kernel.GetAll<ICar>().ToList();
foreach(ICar binding in bindingsList)
{
Trace.WriteLine(string.Format("Service bound to [{1}]", binding.GetType().Name)
}
}
}
}

关于ninject - 如何迭代 Ninject StandardKernel 的已配置绑定(bind)以进行调试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15892367/

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