IOC container AUTOFAC

Source: Internet
Author: User
de jure did not use the example of the IOC

The full name of the IOC is inversion of control, which is called inversion in Chinese. To understand control inversion, you can look at an example of an uncontrolled reversal.

public class Mpgmovielister
   {public
       movie[] Getmpg ()
       {
           var finder = new Listmoviefinder ();
           var allmovies = Finder. FindAll ();

           Return Allmovies.where (M => m.name.endswith (". MPG ")). ToArray ();
       }

 

public class Listmoviefinder
   {public
       list<movie> findall ()
       {return
           new list<movie>
                      {
                          new Movie
                              {
                                  name = ' Die hard.wmv '
                              },
                          new Movie
                              {
                                  name = ' My Name is John.mpg '
                              }
                      };
       }
   }

In the example above, the role of class mpgmovielister is to list all the types of MPG movies, which call the class Listmoviefinder class method FindAll () to get all the movies.

The code looks good enough to fit the current requirements. Ii. the dilemma faced by non-IOC when demand has changed

If, at this time, movie's list gets not directly to create a list fetch, but requires reading from a text file, or a database fetch, or a Web service, what do we do.

The first step is to implement a class, such as Filemoviefinder, to read the movie list from a text file, and then put this line of code in the Mpgmovielister

var finder = new Listmoviefinder ();
Replace into

var finder = new Filemoviefinder ();
Then this line of code will be able to meet the requirements.

The new Mpgmovielister code looks like this:

   public class Mpgmovielister
   {public
       movie[] Getmpg ()
      {
            var finder = new Filemoviefinder ();
           var allmovies = Finder. FindAll ();
           Return Allmovies.where (M => m.name.endswith (". MPG ")). ToArray ();
       }
   

If the underlying--the way in which data is obtained is uncertain, or often changed--is it mpgmovielister to change the code frequently? third, the use of the IOC to solve the problem thoroughly:

Mpgmovielister's functions are all dependent on the specific class, Listmoviefinder,filemoviefinder. When the requirements change, it will cause the Mpgmovielister code to make the corresponding changes.

In other words, mpgmovielister is directly dependent on Listmoviefinder and Filemoviefinder.

Out of the box, Mpgmovielister's function is just to find out from the list of MPG movie, as for movie from where, not mpgmovielister duties, it does not need to care.

The solution-coupling approach is to "rely on abstraction rather than on concrete".

(This example is very similar to our development time persistence layer (data layer) and business logic layer, in fact, the business logic layer does not care about how the data is provided, so the business logic layer should also be coupled with the persistence layer. )

Code after the actual resolution:

public class Mpgmovielister
   {public
       movie[] Getmpg ()
      {
            var finder = Moviefinderfactory.getfinder ();
           var allmovies = Finder. FindAll ();
           Return Allmovies.where (M => m.name.endswith (". MPG ")). ToArray ();
       }
 

public class Moviefinderfactory
{public
     static Imoviefinder Getfinder ()
     {return
         new Filemoviefinder ();
     } 

Public interface Imoviefinder
{
    list<movie> findall ()
}

Here Mpgmovielister relies on the Imoviefinder interface (dependency abstraction), and the actual run-time instantiation is provided by Moviefinderfactory. In this way, different movie data sources require only one class to implement Imoviefinder, and will not have any effect on mpgmovielister.

Here, the IOC has actually been completed, and control initially depends on how the Moviefinder is instantiated in Mpgmovielister, and now it has surrendered control to the outside to provide concrete instance objects.

Here the moviefinderfactory is already a crude IOC container function.

Iv. Summary

The IOC's approach to solving this dependency is the use of object-oriented methods. In the real world, this approach is everywhere.

For example, a car will not rely heavily on a brand of Tyre, and any tyre produced by a company can be used on the car as long as it meets the vehicle's interface.

There is also a computer USB interface, as long as the USB standard with the peripherals, can be connected to the computer use.

Not only does unbinding make the code structure look more reasonable, but another benefit is that each part can be individually unit tested to make unit tests easier to do. This is very useful for a number of highly complex projects to ensure the stability and availability of the project.

The real IOC container is naturally more useful and applicable than the moviefinderfactory above. The next article will introduce a very good IOC framework AUTOFAC.

IOC Container AUTOFAC (2) examples of using custom factory classes to implement the IOC

Let's review the previous code:

//the role of this class is to filter out the MPG type of 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 listmovief
     Inder (); } public class Listmoviefinder:imoviefinder {public list<movie> findall () {return new List<mo  vie> {new Movie {Name
                          = "Die hard.wmv"}, new Movie {
   Name = ' My Name is John.mpg '}}; } public interface Imoviefinder {list<movie> findall ()} 

Here the mpgmovielister has not been coupled with the specific moviefinder, but relies on the specific implementation of the Imoviefinder interface provided by the Moviefinderfactory factory class to fetch movie data.

So as long as the factory class returns a different instance of implementation Imoviefinder, it will be able to get movielister from the list, text, database, Web service ... Gets the data. Second, the transformation code, remove Moviefinderfactory

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

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
{
    list<movie> findall ()

We removed the factory class Moviefinderfactory, modified the Mpgmovielister, added a constructor, and when the constructor required the use of mpgmovielister, we needed to provide a imoviefinder instance. third, the application AUTOFAC substitution 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 kinds of objects we need

* Register the type of object that we will take out of the container later.

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.