Background
With the increasing popularity of Asp.net mvc, there are also a lot of DI containers integrated with Mvc, while the Mini container did not publish the integrated solution, as a result, some netizens may ask these questions from time to time. [Download the source code from here, official address of the Mini container]
Solution
Create a custom factory
Public class NLiteControllerFactory: DefaultControllerFactory
{
Private IServiceLocator ServiceLocator;
Public NLiteControllerFactory (IServiceLocator serviceLocator)
{
This. ServiceLocator = serviceLocator;
}
Protected override IController GetControllerInstance (System. Web. Routing. RequestContext requestContext, Type controllerType)
{
Return (IController) ServiceLocator. Get (controllerType );
}
}
Copy code
Demo
In order to demonstrate the effect, the Artech elder brother used ASP. net mvc creates a Unity-based ControllerFactory blog example. to create an application for maintaining contacts, we use the Contact type defined below to represent contacts, while the IContactRepository interface defines a GetAllContacts method for obtaining all contacts from the storage, defaultContactRepository is the implementation of the IContactRepository interface.
Public class Contact
{
Public string Name {get; set ;}
Public string Gender {get; set ;}
Public string Address {get; set ;}
}
[Contract]
Public interface IContactRepository
{
IEnumerable <Contact> GetAllContacts ();
}
Public class DefaultContactRepository: IContactRepository
{
Public IEnumerable <Contact> GetAllContacts ()
{
Yield return new Contact
{
Name = "Zhang San ",
Gender = "Male ",
Address = "#328, XingHu Street, Su Zhou, Jiang Su Province, PRC ."
};
Yield return new Contact
{
Name = "Li Si ",
Gender = "Female ",
Address = "#328, Jin Ji Hu Road, Su Zhou, Jiang Su Province, PRC ."
};
}
}
Copy code
The contact list is displayed on the homepage of the Web application. For this reason, a HomeController is created, as shown in the following figure. Here we demonstrate constructor injection, So we initialize the Repository attribute through the IContactRepository object specified by the constructor. Call the IContactRepository GetAllContacts method in the Action Method Index to specify a Model for the corresponding View.
Public class HomeController: Controller
{
Public IContactRepository Repository {get; private set ;}
Public HomeController (IContactRepository repository)
{
This. Repository = repository;
}
Public ActionResult Index ()
{
Return View (this. Repository. GetAllContacts ());
}
}
Copy code
Register the Mvc custom controller factory in the Global File
Public class MvcApplication: System. Web. HttpApplication
{
Public static void RegisterGlobalFilters (GlobalFilterCollection filters)
{
Filters. Add (new HandleErrorAttribute ());
}
Public static void RegisterRoutes (RouteCollection routes)
{
Routes. IgnoreRoute ("favicon. ico ");
Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");
Routes. MapRoute (
"Default", // Route name
"{Controller}/{action}/{id}", // URL with parameters
New {controller = "Home", action = "Index", id = UrlParameter. Optional} // Parameter defaults
);
}
Protected void Application_Start ()
{
AreaRegistration. RegisterAllAreas ();
RegisterGlobalFilters (GlobalFilters. Filters );
RegisterRoutes (RouteTable. Routes );
// Create a Mini container
NLiteEnvironment. Refresh ();
// Set the default life cycle of the component to temporary.
LifestyleType. Default = LifestyleFlags. Transient;
// Register the contact warehouse component
ServiceRegistry. Register <defacontcontactrepository> ();
// Set the custom controller Factory
ControllerBuilder. Current. SetControllerFactory (new NLiteControllerFactory (ServiceLocator. Current ));
}
}
Copy code
The Index. cshtml code is as follows. This is a View of the Model type IEnumerable <Contact>, which lists all the Contact information.
@ Model IEnumerable <NLite. Mvc. Models. Contact>
@{
ViewBag. Title = "Index ";
}
<H2> Contact List
<Div>
<Ul>
@ Foreach (var contact in this. Model)
{
<Li>
<H3> @ contact. Name <P> Gender: @ contact. Gender </p>
<P> Address: @ contact. Address </p>
<Hr/>
</Li>
}
</Ul>
</Div>
Copy code
Running Browser display
From Fengyun