First, preface
Using Unity's lightweight Dependency injection container, described in the previous article, this article describes the use of unity Dependency injection controllers and log properties in the controller on MVC.
Implement the new two interfaces provided in MVC: Idependencyresolver and Icontrolleractivator
Second, the Code implementation
Customizing the method of creating the Customcontrolleractivator class to implement the Icontrolleractivator interface
Public class Customcontrolleractivator:icontrolleractivator { IController icontrolleractivator.create (System.Web.Routing.RequestContext requestcontext, Type Controllertype) { return as IController; homecontrollericontroller } } created from the container
Also create a Unitydependencyresolver class to implement the GetService and GetServices methods of the Idependencyresolver interface
Public classunitydependencyresolver:idependencyresolver {Iunitycontainer container; Publicunitydependencyresolver (Iunitycontainer container) { This. Container =container; } Public ObjectGetService (Type servicetype) {Try{ //start HomeController Controller, you will create HomeController,
and HomeController has a public ILogger Logger {get; set;} Log properties, which hit the [Dependency] feature,
and the Getunitycontainer () method has also been registered to the Log property Flatfilelogger, so the default creation of HomeController , the log attributes are injected Flatfilelogger returncontainer. Resolve (servicetype); } Catch { return NULL; } } Publicienumerable<Object>getservices (Type servicetype) {Try { returncontainer. ResolveAll (servicetype); } Catch { return Newlist<Object>(); } } }
With these two classes defined, we find Global.asax.cs and add a private method in it Getunitycontainer ()
Private Iunitycontainer Getunitycontainer () { new unitycontainer () . Registertype<icontrolleractivator, customcontrolleractivator>() . Registertype<ilogger, flatfilelogger>(); return container; }
Then add the following code to the Application_Start method, first get container through the Getunitycontainer method, and setting the current resolver is our own implementation of the Unitydependencyresolver.
protected void Application_Start () { = getunitycontainer (); Dependencyresolver.setresolver (new unitydependencyresolver (Container)); }
In the controller we only need to add a [Dependency] feature, we can easily get into the logger we injected.
public class Homecontroller:controller {[Dependency] public ILogger L Ogger {get ; set public ActionResult Index () { Viewbag.message = I'm coming!!! ; Logger.write ( hahaha " ); return View (); } }
Using unity to implement dynamic injection on MVC