ASP. NET MVC Dependency injection
Comrades, very fast IOC register interface and inject MVC Controller, steps are as follows:
To install the UNITY.MVC NuGet package in your project, open the package Manager console to install it.
Next we can see two class files UnityConfig.cs and UnityMvcActivator.cs, interface registration need to write your interface instance in UnityConfig.cs, UnityMvcActivator.cs It will help you to automatically resolver, don't worry, this tool is too brain-free, need to do not much
1. Registering the interface
public static class Unityconfig {#region Unity Container private static lazy<iunitycontainer> con Tainer = new Lazy<iunitycontainer> (() = {var container = new UnityContainer (); Registertypes (container); return container; }); <summary>//Configured Unity Container. </summary> public static Iunitycontainer Container = Container. Value; #endregion//<summary>//registers the type mappings with the Unity container. </summary>//<param name= "container" >the unity container to configure.</param>/// Lt;remarks>//There is no need to register concrete types such as controllers or///API Controllers (U Nless want to change the defaults), as Unity///allows resolving a concrete type even if it is not previously Registered. </remarks> public static void Registertypes (Iunitycontainer container) {//Note:t o load from Web. config uncomment the line below. Make sure to add a unity.configuration to the using statements. Container. Loadconfiguration (); Todo:register your type ' s mappings here. Container. Registertype<iproductrepository, productrepository> (); Container. Registertype<irepository, repositoryimpl> (); }
2. Inject the interface to the controller
public class Homecontroller:controller { private irepository _repository; Public HomeController (irepository repository) { _repository = repository; } Public ActionResult Index () { var result = _repository. Test (); return View (result);
}
3. Launch IOC initialization, code in Global.asax
public class MvcApplication:System.Web.HttpApplication { protected void Application_Start () { Arearegistration.registerallareas (); Filterconfig.registerglobalfilters (globalfilters.filters); Routeconfig.registerroutes (routetable.routes); Bundleconfig.registerbundles (bundletable.bundles); Unityconfig.registertypes (New UnityContainer ()); } }
Juvenile F5 Start your program, witness the miracle of the moment, the fastest to build the. NET MVC Ioc interface instance and the controller's dependency injection.
C # Ioc ASP Dependency Injection