First, the untiy framework is introduced. Can be installed directly in the NuGet Package Manager.
New unitycontrollerfactory for inheriting defaultcontrollerfactory:
Override virtual method GetControllerInstance.
Public classUnitycontrollerfactory:defaultcontrollerfactory { PublicIunitycontainer UnityContainer {Get;Private Set; } Publicunitycontrollerfactory (Iunitycontainer unitycontainer) { This. UnityContainer =UnityContainer; } protected OverrideIController getcontrollerinstance (RequestContext requestcontext, Type controllertype) {if(NULL==Controllertype) { return NULL; } return(IController) This. Unitycontainer.resolve (Controllertype); } }
Then the unity is activated in Global.asax:
protected voidApplication_Start () {arearegistration.registerallareas (); Webapiconfig.register (globalconfiguration.configuration); Filterconfig.registerglobalfilters (globalfilters.filters); Routeconfig.registerroutes (routetable.routes); //as followsUnityContainer UnityContainer =NewUnityContainer (); //Iemployeerepository is the storage layer that needs to be relied uponUnitycontainer.registertype<iemployeerepository, employeerepository>(); Unitycontrollerfactory controllerfactory=Newunitycontrollerfactory (UnityContainer); ControllerBuilder.Current.SetControllerFactory (controllerfactory); }
Next we need to develop a dependency property injection method in the controller.
The dependency feature is to tell us this dependency property
[Dependency] Public Get set; }
There is also an activation method based on the Ninject IOC framework through Icontrolleractivator or Idependencyresolver.
...
MVC4 controllerfactory based on Unity IOC framework