ASP.NET MVC Implements Ioc with Unity

Keywords: ASP.NET Unity Database xml

Why does this article exist?

Recently, Ioc was used in ASP.NET MVC project and Unity was selected as the container component of dependency injection. Relevant articles on the Internet were found to simply implement dependency injection, but it was found that the way to register container injection by file configuration was not applicable, because most articles on the Internet used Unity 4.0.1 version, and the latest Unit. Version y is 5.8.6, and the code for container injection using configuration is quite different.

Ioc and Unity

IOC (Inversion of Control), or "Inversion of Control", is a design idea. With IoC, the control of creating and searching dependent objects is given to the container, and the container injects the combined objects. So the object and the object are loosely coupled, which is also convenient for testing and functional reuse. More importantly, it makes the whole architecture of the program very flexible.

Unity is a lightweight dependency injection container developed by Microsoft Patterns & Practices.

Code preparation

Create a new MVC project with the default name Web Application 1. Create the following three new classes in Model:

public class User
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
}
public interface IUserDao
{
    List<User> GetAllUsers();
}
public class EFUserDao : IUserDao
{
    public List<User> GetAllUsers()
    {
        List<User> list = new List<User>();
        //Use EF Reading data from a database...
        return list;
    }
}

 

Write code in Index() in HomeController:

using WebApplication1.Models;
public class HomeController : Controller
{
    public ActionResult Index()
    {
        IUserDao dao = new EFUserDao();
        var list = dao.GetAllUsers();

        //do something...

        return View();
    }
}

The above code mainly implements the acquisition of user list data from the database to the controller.

Using Unity

Right-click on the project reference, manage the Nuget package, search Unity and install it.

 

Code changes in HomeController

using WebApplication1.Models;
using Unity;
public class HomeController : Controller
{
    public ActionResult Index()
    {
        IUnityContainer container = new UnityContainer();
        container.RegisterType<IUserDao, EFUserDao>();
        var dao = container.Resolve<IUserDao>();

        var list = dao.GetAllUsers();
        //do something...

        return View();
    }
}

The above code first declares a Unity container, then registers the required objects, and finally calls.

In the above way, every time GetAllUsers() is used, it needs to be declared. It should be encapsulated here. Unity's use in ASP.NET MVC has encapsulated the code.

ASP.NET MVC uses Unity

Use Nuget to install Unity.MVC.

 

After installation, UnityMvcActivator.cs and UnityConfig.cs files will be automatically generated in the ~/App_Start/ directory.

Open the UnityConfig file and 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>();
}

Attention citation

using WebApplication1.Models;

 

Modify the HomeController code (injected with constructors)

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 approach is to write dependency injection into code. However, it is not flexible. Every group of classes is added, the code is registered and compiled in UnityConfig. What we need more is to register the type in the configuration file.

Use configuration files

Modify the code of 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 quote

using Microsoft.Practices.Unity.Configuration;

 

Change the configuration of Web.Config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
  </configSections>
  <unity>
    <containers>
      <container>
        <types>
          <type type="WebApplication1.Models.IUserDao, WebApplication1" mapTo="WebApplication1.Models.EFUserDao, WebApplication1" />
        </types>
      </container>
    </containers>
  </unity>
  ......
</configuration>

Run the site and get the user list data successfully.

extend

If the requirement changes, you need to use ADO.NET to operate the database. Just build a class of SQL UserDao, inherit from IUserDao, and then modify the registration type in the configuration file.

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

 

The author uses VS2017 for operation.

Posted by BluePhoenixNC on Sun, 23 Dec 2018 12:03:06 -0800