IOC container AUTOFAC (ii)

Source: Internet
Author: User

Review the previous Code

The function of this class is to filter out the MPG type of the movie public class mpgmovielister:imoviefinder{public  movie[] Getmpg ()  {       var finder = Moviefinderfactory.getfinder ();//Here Call the factory class to get the concrete instance, get a movie list       var allmovies = finder. FindAll ();       Return Allmovies.where (M = M.name.endswith (". MPG ")). ToArray ();   }} public class moviefinderfactory{public     static Imoviefinder Getfinder ()     {         return new Listmoviefinder ();     } public class listmoviefinder:imoviefinder{public   list<movie> FindAll ()   {       return new list< Movie>                  {                      new movie                          {                              name = ' Die hard.wmv '                          },                      new movie                      {                          name = "My Name is John.mpg "                      }                 };}}   Public interface Imoviefinder {list<movie> FindAll ()}
Second, the transformation code, the removal of moviefinderfactory

Before applying AUTOFAC to replace moviefinderfactory, we first remove the moviefinderfactory from the code, and the following code is the change:

public class mpgmovielister{    private readonly imoviefinder _moviefinder;    Added constructor, parameter is Imoviefinder object public    mpgmovielister (Imoviefinder moviefinder)    {         _moviefinder = Moviefinder;    }    Public movie[] Getmpg ()    {     var allmovies = _moviefinder.findall ();     Return Allmovies.where (M = M.name.endswith (". MPG ")). ToArray ();    }} public interface imoviefinder{    

We removed the factory class Moviefinderfactory, modified the Mpgmovielister, added a constructor, and the constructor required a Imoviefinder instance to be provided when using Mpgmovielister.

Third, the application of AUTOFAC alternative factory class

Apply AUTOFAC to transform the above code.

First step: Add AUTOFAC references from NuGet

Step Two:

* Create a Containerbuilder object (Containerbuilder literally means to create a container (container), and Conainter is where we take all the objects we need)

* Register the type of object that will be removed from the container after us.

The code is like this:

var builder = new Containerbuilder ();//builder. Registertype<listmoviefinder> (). Asimplementedinterfaces ();//register Listmoviefinder type, where the asimplementedinterfaces means to register as an interface builder.registertype< Mpgmovielister> ();//Register Mpgmovielister type

* Create container

_container = Builder. Build ();

Step three: Use the _container container in your program:

var lister = _container. Resolve<mpgmovielister> (); foreach (Var movie in Lister. Getmpg ()) {     

Understand what AUTOFAC has done for us in the back:

First, we register the types Listmoviefinder and mpgmovielister so that the container can know how to create the two types of instances. (The class is actually a template for creating objects, and when we register the template with AUTOFAC, it will follow this template to provide examples for us)

In the following code, we call the Resolve method and take out an instance of the Mpgmovielister.

_container. Resolve<mpgmovielister> ();

Here's another explanation, for the Mpgmovielister type, we provide a type for AUTOFAC, but when AUTOFAC creates an instance of Mpgmovielister and calls its constructor, it encounters a problem:

Its constructor needs to provide an instance of Imoviefinder as a parameter, and the clever autofac to find it in his own container to see if there is no way to provide an instance of Imoviefinder.

This time AUTOFAC will find that we have registered Listmoviefinder, and through the Asimplementedinterfaces () method, indicates that the interface Imoviefinder provide an instance.

So AUTOFAC creates an instance of Listmoviefinder as the argument that is given to the constructor when the Mpgmovielister is created.

Builder. Registertype<listmoviefinder> (). Asimplementedinterfaces ();
Iv. when demand changes, how can AUTOFAC respond?

In the above example, our class Listmoviefinder implements the Imoviefinder interface, which is actually running, and it is provided by the data.

What if we were to get the data from the database at this time?

It is very simple to create a class dbmoviefinder inherit the Imoviefinder interface and then register it with AUTOFAC. This makes it very easy for the program to switch to fetching data from the database.

The code for registering related changes is this:


Builder. Registertype<mpgmovielister> (); _container = Builder. Build ();
V. The impact of AUTOFAC on the program architecture

Common program architectures are: UI layer, business logic layer, persistence layer (data layer).

We can use AUTOFAC as an intermediary between different tiers, so that the UI layer relies on the abstraction of the business logic layer, and the business logic layer relies on the interface of the persistence layer, and the instances in the actual running process are provided by AUOTFAC.

This allows the dependencies between different tiers to be removed, and the operation of all registered types is implemented in a core function or core class, so it is very convenient to change the dependencies between them if you modify the function or class.

For example, in a large project, the persistence layer and the business logic layer are developed in parallel and are developed by different teams, so how do people in the business logic development team start without persistent layer code?

As long as we define the interface of the persistence layer, the business logic team will write some stub classes (piles) to implement these interfaces, so that these stub classes replace the true persistence layer, all you have to do is simply register these stub types in the AUTOFAC. It is also very easy to do unit testing of the business logic layer at the same time.

Vi. Summary

As can be seen from the above example, the use of IOC for complex projects is very meaningful and can build a good level of development for us.

At the same time, in the use of the process, you can also find that AUTOFAC has the following advantages:

1. You can use C # code to complete the registration configuration, which is very convenient and easy to debug. (using XML configuration, often prone to formatting errors, or other problems, very difficult to debug and troubleshooting)

2. Very smart, able to automatically assemble (find the necessary parameters of the constructor function, will solve their own)

IOC container AUTOFAC (ii)

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.