ASP. NET MVC uses unity to implement IOC

Source: Internet
Author: User

Why is this article

Recently learning to use the IOC in the ASP. NET MVC project, we chose Unity as the container component of dependency injection, found the relevant articles on the Internet to implement the dependency injection, but wanted to register the container injection in the way of the file configuration, and found that the relevant article implementation method was not applicable. Since most of the articles on the web are in Unity 4.0.1, the latest version of Unity is 5.8.6, and the code for container injection using configuration is different.

IOC and Unity

The IOC (inversion of control), or "inversion of controls", is a design idea. With IOC, the control of creating and locating dependent objects is given to the container, which is injected by the container, so that the object is loosely coupled with the object, which facilitates testing, facilitates functional reuse, and, more importantly, makes the entire architecture of the program very flexible.

Unity is a lightweight, dependency injection container developed by the Microsoft patterns & practices department.

Code preparation

Create a new MVC project, using the default named WebApplication1. Create the following 3 classes in model:

 Public classuser{ Public intId {Get;Set; }  Public stringUserName {Get;Set; }  Public stringPassword {Get;Set; }  Public stringEmail {Get;Set; }}
 Public Interface iuserdao{    List<User> GetAllUsers ();}
 Public class efuserdao:iuserdao{    public list<user> GetAllUsers ()    {        List New list<user>();         // use EF to read data        from the database ... return list;    }}

Write code in Index () in HomeController:

using Webapplication1.models;  Public class homecontroller:controller{    public  actionresult Index ()    {        new Efuserdao ();         var list = dao. GetAllUsers ();         // Do something        ... return View ();    }}

The above code mainly implements retrieving the user list data from the database into the controller.

Using Unity

Right-click on the project reference, manage the NuGet package, search for unity and install.

Code Churn in HomeController

usingWebapplication1.models;usingUnity; Public classhomecontroller:controller{ PublicActionResult Index () {Iunitycontainer container=NewUnityContainer (); Container. Registertype<iuserdao, efuserdao>(); varDAO = container. Resolve<iuserdao>(); varList =DAO.        GetAllUsers (); //Do something ...        returnView (); }}

The above code declares a unity container first, then registers the desired object and finally calls it.

In the above way, each time you use GetAllUsers () before you need to declare, here should be encapsulated. The use of unity in ASP. NET MVC has already encapsulated the code.

ASP. NET MVC uses unity

Install UNITY.MVC using NuGet.

The UnityMvcActivator.cs and UnityConfig.cs files are automatically generated in the ~/app_start/directory when the installation is complete.

Open the Unityconfig file, modify the code of the Registertypes () method

 Public Static void registertypes (Iunitycontainer container) {    //  note:to 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<iuserdao, efuserdao>();}

Note reference

using Webapplication1.models;

Modifying the HomeController code (using constructor injection)

 Public class homecontroller:controller{    Iuserdao _iuserdao;      Public HomeController (Iuserdao Iuserdao)    {        this. _iuserdao = Iuserdao;    }       Public actionresult Index ()    {        var list = _iuserdao.getallusers ();         // Do something        ... return View ();    }}

This method writes the dependency injection in the code. It is not flexible, however, to register and compile the code once for each set of classes that are added to the unityconfig. What we need more is to register the type in the configuration file.

Using configuration Files

To modify the code for the Registertypes () method in the Unityconfig file:

 Public Static void registertypes (Iunitycontainer container) {    //  note:to 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<iuserdao, efuserdao> ();}

Need to reference

using Microsoft.Practices.Unity.Configuration;

To change the configuration of Web. config:

<?XML version= "1.0" encoding= "Utf-8"?><Configuration>  <configsections>    < Sectionname= "Unity"type= "Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, unity.configuration"/>  </configsections>  <Unity>    <Containers>      <Container>        <Types>          <typetype= "WebApplication1.Models.IUserDao, WebApplication1"Mapto= "WebApplication1.Models.EFUserDao, WebApplication1" />        </Types>      </Container>    </Containers>  </Unity>  ......</Configuration>

Run the site and obtain the user list data successfully.

Extended

If the requirements change, to use ADO to manipulate the database, just build a Sqluserdao class, inherit from Iuserdao, and then modify the registration type in the configuration file to

<type= "WebApplication1.Models.IUserDao, WebApplication1"  mapto = "WebApplication1.Models.SQLUserDao, WebApplication1" />

The author uses the VS2017 to operate.

ASP. NET MVC uses unity to implement IOC

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.