下载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容器 }