如何迭代Ninject StandardKernel配置的绑定到调试?

时间:2013-04-09 02:38:11

标签: ninject ioc-container autowired

在我的Ninject绑定模块中,

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]
    }
}

我需要进行健全性检查才能看到我成功绑定到我的服务的类型。我无法访问绑定类型的类型名称。而不是[BindingTarget],我希望看到[Mercedes][Ferrari]等......

有没有好的和/或常用的方法呢?

1 个答案:

答案 0 :(得分:0)

在你的IocKernel中,我只是添加一个方法来GetAll给定类型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)
                }
            }
        }              
    }