In MVC4, many people use Ninject to implement DI.
Here (http://q.cnblogs.com/q/37471/), the boss mentioned one:
[assembly: PreApplicationStartMethod(typeof(BootStrapper.Initializer), "Initialize")]
However, I have not yet completed how the BootStrapper came from. Which DDL statements are referenced?
After two hours of study, the solution is as follows:
1. First, add the following reference: (The DAL project does not need to be added to the WebUI project)
1) BootStrapper. Ninject
2) Ninject.
Use nuget to add other associated references.
2. Create NinjectDependencyResolver. cs under WebUI
The content is as follows:
public class NinjectDependencyResolver : IDependencyResolver { private IKernel ninjectKernel; public NinjectDependencyResolver() { ninjectKernel = (IKernel)Bootstrapper.Container; } public object GetService(Type serviceType) { return ninjectKernel.TryGet(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { return ninjectKernel.GetAll(serviceType); } }
3. Controller uses constructor injection.
public class UserController : Controller { private IUserRepository repository; public UserController(IUserRepository repo) { repository = repo; } // // GET: /User/ public ViewResult Index() { return View(repository.AllUsers()); } }
If property injection is used:
public class UserController : Controller { [Inject] public IUserRepository Repository{get;set;} // // GET: /User/ public ViewResult Index() { return View(Repository.AllUsers()); } }
This looks more concise.
4. Modify Application_Start in Global. asax. cs.
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); Bootstrap.Bootstrapper.With.Ninject().UsingAutoRegistration().Start(); Bootstrap.Bootstrapper.IncludingOnly.Assembly(Assembly.GetAssembly(typeof(User))) .Start(); //ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); DependencyResolver.SetResolver(new NinjectDependencyResolver()); BundleTable.Bundles.RegisterTemplateBundles(); }
Explanation:
1) Bootstrap. bootstrapper. with. ninject (). usingAutoRegistration (). start (); -- this is mainly used to automatically register all types. The Convention is that the default Implementation of IMyType is MyType (less than one I ).
Like: Kernel. Bind <IMyType> (). To <MyType> ();
However, in our example, you do not need To write the following statement: Kernel. Bind <IMyType> (). To <MyType> ();. You just need to maintain this convention.
2) Bootstrap. Bootstrapper. IncludingOnly. Assembly (Assembly. GetAssembly (typeof (User )))
. Start (); -- this is mainly used to load our DAL files without scanning other files to improve efficiency.
Hope to give others a more reference
Enjoy it ,:)