Ninject 自动注册

首先这个问题我纠结了很久,看到autofac强大的自动注册功能,我感觉Ninject弱爆了,不过Ninject自带属性注册,感觉很方便,所以还在纠结Ninject

传统的绑定方式

public class BLLModule:NinjectModule
    {
        public override void Load()
        {
            Bind<Itb_sys_ModuleBLL>().To<tb_sys_ModuleBLL>().InSingletonScope();
            Bind<Itb_sys_ItemBLL>().To<tb_sys_ItemBLL>().InSingletonScope();
            Bind<Itb_item_CompanyBLL>().To<tb_item_CompanyBLL>().InSingletonScope();
            Bind<Itb_item_DepartmentBLL>().To<tb_item_DepartmentBLL>().InSingletonScope();
            Bind<Itb_item_UserBLL>().To<tb_item_UserBLL>().InSingletonScope();
            Bind<Itb_item_RoleBLL>().To<tb_item_RoleBLL>().InSingletonScope();
        }
    }

  一个接口对应一个实体类,太费劲了。

自动绑定方式:

    /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind(scanner => scanner.From("IBLL","BLL")
               .Select(IsServiceType)
               .BindDefaultInterface()
               .Configure(binding => binding.InSingletonScope())
           );
            kernel.Bind(scanner => scanner.From("IDao", "Dao")
               .Select(IsServiceType)
               .BindDefaultInterface()
               .Configure(binding => binding.InSingletonScope())
           );         
        }
        private static bool IsServiceType(Type type)
        {
            return type.IsClass && type.GetInterfaces().Any(intface => intface.Name == "I" + type.Name);
        }

这样就OK了,不用在手动棒了,所有的接口都注册好了

实现方式:

1、vs2010 Nuget安装Ninject.Mvc3

2、vs2010 Nuget安装Ninject.Extensions

就这样好了。太他娘的简单了。

 

posted @ 2015-03-09 19:23  Taffy++  阅读(732)  评论(0编辑  收藏  举报