asp.net MVC uses the unity Ioc Container

Source: Internet
Author: User
Tags abstract add bool interface net string static class version

In MVC, the controller relies on the model to process the data, or it can be said to execute the business logic. We can use Dependency injection (DI) in the control layer to separate the model layer, this way to use the repository mode, in the domain-driven design (DDD), repository translation for warehousing, as the name implies, is the storage of things, can be understood as a storage for encapsulation, A mechanism for reading and finding behavior that simulates a collection of objects. Using Dependency Injection (DI) is the management of repository to solve the coupling problem between it and the controller, let's do a simple example step-by-step.

Install Unity

First we need to create a new Unitymvcdemo project (asp.net MVC4.0), select Tools-Library Package Manager-Package Management console, enter the "install-package unity.mvc4" command, VS2010 may need to install NuGet first.

or through the tool-Library Package Manager-Manage the solution's NuGet package and install it online by searching for "Unity.mvc4".

You may experience the following error during Setup:

Depending on the exception information, it is certain that the. NET Framework version of the project cannot install unity, and this installation vs will automatically search for the latest version of unity, but the latest version is often available. NET Framework version requirements, do not know whether to specify the unity version of the installation, you can see that we are installed Unity3.0 version, modify the project. NET Framework version is 4.5, reinstall is OK.

After the installation of Unity succeeded, we found that there were more than two references to "Microsoft.Practices.Unity" and "Microsoft.Practices.Unity.Configuration" in the project. There is also a bootstrapper class file, bootstrapper translated into a boot program, which is the IOC container.

public static Class Bootstrapper
{
public static Iunitycontainer initialise ()
{
var container = Buildunitycontainer ();

Dependencyresolver.setresolver (new Unitydependencyresolver (container));

return container;
}

private static Iunitycontainer Buildunitycontainer ()
{
var container = new UnityContainer ();

Register all your components with the container
It isn't necessary to register your controllers

e.g. container. Registertype ();
Registertypes (container);

return container;
}

public static void Registertypes (Iunitycontainer container)
{

}
}

Add Service Layer

First we add a article entity class:


Article entity classes

public class Article
{
public int Id {get; set;}
public string Title {get; set;}
public string Author {get; set;}
public string Content {get; set;}
Public DateTime createtime {get; set;}
}

General repository have some similar operations, such as additions and deletions, we can abstract it as a iarticlerepository interface, so that the controller relies on the abstract interface, and does not depend on the implementation of the specific repository class, in line with the dependency inversion principle, We can use unity for dependency injection.


Iarticlerepository interface

public interface Iarticlerepository
{
Ienumerable GetAll ();
Article get (int id);
Article Add (Article item);
BOOL Update (Article item);
BOOL Delete (int id);
}

Create Articlerepository, rely on the Iarticlerepository interface, and implement basic operations.

public class Articlerepository:iarticlerepository
{
Private list articles = new list ();

Public Articlerepository ()
{
Add Demo data
ADD (new Article {Id = 1, Title = "UnityMVCDemo1", Content = "Unitymvcdemo", Author = "Xishuai", Createtime = DateTime.Now });
ADD (new Article {Id = 2, Title = "UnityMVCDemo2", Content = "Unitymvcdemo", Author = "Xishuai", Createtime = DateTime.Now });
ADD (new Article {Id = 3, Title = "UnityMVCDemo2", Content = "Unitymvcdemo", Author = "Xishuai", Createtime = DateTime.Now });
}

Get all articles


Public IEnumerable GetAll ()
{
return articles;
}

Get an article by ID



Public Article get (int id)
{
Return Articles.find (p => p.id = Id);
}

Add an article



Public Article ADD (Article Item)
{
if (item = NULL)
{
throw new ArgumentNullException ("item");
}
Articles.add (item);
return item;
}

Update articles



public bool Update (Article Item)
{
if (item = NULL)
{
throw new ArgumentNullException ("item");
}

int index = Articles.findindex (p => p.id = = Item. ID);
if (index = = 1)
{
return false;
}
Articles.removeat (index);
Articles.add (item);
return true;
}

Delete an article



public bool Delete (int id)
{
Articles.removeall (p => p.id = Id);
return true;
}
}

Iarticlerepository Type Mappings

Once the above work is done, we need to add this type mapping in the Buildunitycontainer method in bootstrapper.

 private static Iunitycontainer Buildunitycontainer ()         {  &

nbsp;         var container = new UnityContainer ();            //Register all your components with the container Here            //It isn't necessary to register your Controllers             container.

Registertype ();            //e.g. container. Registertype ();           

     registertypes (container);
            return container;        } 

We can also add type mappings in the configuration file, UnityContainer the associated type according to the configuration information, so we just change the configuration file, of course, this is the recommended method, configuration file:










Note that the configsections node should be placed at the first node under the Configuration node, and the configuration file configuration reference http://www.cnblogs.com/xishuai/p/3670292.html for unity, Load configuration file code:

1     unityconfigurationsection configuration = (unityconfigurationsection) configurationmanager.getsection ( Unityconfigurationsection.sectionname); 2     configuration. Configure (Container, "Defaultcontainer");

The above code replaces the Registertype method used above.

Service Injection to Controller

In Articlecontroller we use constructor injection, and, of course, attribute injection and method injection, we can see that Articlecontroller relies on the abstract iarticlerepository interface, Instead of relying on articlerepository specific implementation classes.

public class Articlecontroller:controller
{
ReadOnly iarticlerepository repository;
Constructor injection
Public Articlecontroller (Iarticlerepository repository)
{
This.repository = repository;
}

Public ActionResult Index ()
{
var data = Repository. GetAll ();
return View (data);
}
}

Global.asax Initialization

After doing the above work, we need to add dependency injection initialization in the Application_Start method in Global.asax.

Note:for instructions on enabling IIS6 or IIS7 Classic mode,
Visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication:System.Web.HttpApplication
{
protected void Application_Start ()
{
Arearegistration.registerallareas ();

Webapiconfig.register (globalconfiguration.configuration);
Filterconfig.registerglobalfilters (globalfilters.filters);
Routeconfig.registerroutes (routetable.routes);

Bootstrapper.initialise ();
}
}

Sample code Download: http://pan.baidu.com/s/1qWoCy9e.



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.