6

在我的 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], 等等...

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

4

1 回答 1

0

在您的 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)
                }
            }
        }              
    }
于 2016-08-12T10:36:28.970 回答