下载Niject.dll
2.新建 控制器工厂
public class ControllerFactory : DefaultControllerFactory { private IKernel ninjectKernel; public NinjectControllerFactory() { ninjectKernel = new StandardKernel(); AddBindings(); } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType); } private void AddBindings() { // todo:后面再来添加绑定 _kernel.Bind<IUserService>().To<UserService>(); _kernel.Bind<IRoleService>().To<RoleService>(); _kernel.Bind<IDepartmentService>().To<DepartmentService>(); _kernel.Bind<IUserRoleService>().To<UserRoleService>(); _kernel.Bind<IUserDepartmentService>().To<UserDepartmentService>(); _kernel.Bind<IDepartmentTypeService>().To<DepartmentTypeService>(); _kernel.Bind<IProjectInforService>().To<ProjectInforService>(); _kernel.Bind<IPerformanceService>().To<PerformanceService>(); _kernel.Bind<IUserRepository>().To<UserRepository>(); _kernel.Bind<IRoleRepository>().To<RoleRepository>(); _kernel.Bind<IDepartmentRepository>().To<DepartmentRepository>(); _kernel.Bind<IUserRoleRepository>().To<UserRoleRepository>(); _kernel.Bind<IUserDepartmentRepository>().To<UserDepartmentRepository>(); _kernel.Bind<IDepartmentTypeRepository>().To<DepartmentTypeRepository>(); _kernel.Bind<IProjectInforRepository>().To<ProjectInforRepository>(); _kernel.Bind<IPerformanceRepository>().To<PerformanceRepository>(); _kernel.Bind<DataContext>().To<DataContext>(); } } 3 注册 protected void Application_Start() { ...... //设置Controller工厂 ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); } 还有一种方法属性注入 public class NinjectDependencyResolver:System.Web.Mvc.IDependencyResolver { private readonly IKernel _kernel; public NinjectDependencyResolver() { _kernel=new StandardKernel(); AddBindings(); } private void AddBindings() { //同上 } public object GetService(Type serviceType) { return _kernel.TryGet(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { return _kernel.GetAll(serviceType); } } 3 注册 protected void Application_Start() { DependencyResolver.SetResolver(new Code.NinjectDependencyResolver());//注册Ioc容器 }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。