IOC container AUTOFAC Series (2)--integrated AUTOFAC (RPM) in ASP.

Source: Internet
Author: User

After the introduction of the previous Dragonfly water, this article quickly started with an example AUTOFAC, showing what will happen when ASP. NET MVC introduces AUTOFAC.

Create ASP. NET MVC and introduce AUTOFAC

First, create an MVC site, for the sake of convenience, choose the initial band HomeController and AccountController. The class library is then introduced through NuGet or by downloading to the AUTOFAC website. Personal recommendation of the former, because from VS2010, has built-in visualization of the NuGet features, easy to use. As shown in the following:

This is vs2012 interface, click "Manage NuGet Packages ...", pop-up form as follows, in the upper right corner of the search box, enter "AUTOFAC", find the corresponding library click Install. The library that needs to be applied here has two "AUTOFAC" and "Autofac ASP. NET MVC3 integration".

AUTOFAC implementation of automatic controller injection

Now HomeController needs to use the logging function. Following the previous Ilog interface, it is assumed that there is a Ilog implementation class--txtlog, which is placed in the Services folder under the root directory.

Double-click code Select All
1 2 3 4 5 6 7 public class TxtLog:ILog    {        public void Save(string message)        {            //save as txt        }    }

HomeController need to add a ilog type variable, in order to visually see the class name, I assign the _log class name to Viewbag.logtypename and display it. The code is as follows:

Double-click code Select All
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class HomeController : Controller    {        private ILog _log;                    public HomeController(ILog log)        {            _log = log;        }                public ActionResult Index()        {            ViewBag.Message = "Welcome to ASP.NET MVC!";            ViewBag.LogTypeName = _log.GetType().Name;                           return View();        }                //....

Next, add the following code to the corresponding page (sorry, this is described in English, because my code highlighting plugin cannot display Chinese):

At this point the running program will give an error because HomeController cannot find the parameterless constructor, and we have not given _log any type of instance.

Now let AUTOFAC play a role, add the configuration code in the Application_Start method of the global file, as follows:

Double-click code Select All
1 2 3 4 5 6 7 8 9 10 11 12 protected void Application_Start()    {        ......                ContainerBuilder builder = new ContainerBuilder();        builder.RegisterControllers(Assembly.GetExecutingAssembly());        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())            .AsImplementedInterfaces();                    var container = builder.Build();        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));    }

Regardless of the meaning, after adding these code, and then run the program, you will find that the HomeController ilog variable is given an instance of the Txtlog type, and we did not do any new operation, the results such as:

AUTOFAC Response to demand changes

Look back at the code for the config file in Application_Start:

    1. Builder. Registercontrollers registers all controller classes in the current assembly.

    2. Builder. Registerassemblytypes registers all classes in the current assembly.

If the demand changes now, we need to change all the Txtlog to DBLog, what should we do? First add the DBLog class, as follows:

Double-click code Select All
1 2 3 4 5 6 7 public class DbLog:ILog    {        public void Save(string message)        {            //save to Db.        }    }

Then add the following code at the end of the Application_Start method:

Double-click code Select All
1 builder.RegisterType<DbLog>().As<ILog>();

Run the program and see the page as follows:

It can be seen that the type of ilog has become dblog. But why should we emphasize the end? In fact, DBLog has been registered through Builder.registerassemblytypes once, if the same type or interface is registered multiple times (such as the ilog here), in the AUTOFAC will be saved as a list, if only one, Then AUTOFAC will return the latest one from the list.

To prove that, we add a variable in HomeController, type Ienumerable<ilog>, and then display all the class names in the list, separated by commas.

Double-click code Select All
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class HomeController : Controller    {        private ILog _log;        private IEnumerable<ILog> _logList;        public HomeController(ILog log,IEnumerable<ILog> logList )        {            _log = log;            _logList = logList;        }                public ActionResult Index()        {            ViewBag.Message = "Welcome to ASP.NET MVC!";            ViewBag.LogTypeName = _log.GetType().Name;            ViewBag.LogTypeNames = _logList.Select(x => x.GetType().Name).Aggregate((x, y) => x+","+y );                            return View();        }

To run the program, the page appears as follows:

As you can see, there are three types registered for the Ilog interface. The first two through builder. Registerassemblytypes registration, the last one we added manually.

But the repetition of the type of registration is always not elegant, so the actual development is not recommended to register all classes, conditional filtering. Open the source of AUTOFAC, see the Builder we used above. Registercontrollers will find that this is the idea inside the method:

Double-click code Select All
1 2 3 4 5 6 7 8 9 public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle>        RegisterControllers(            this ContainerBuilder builder,            params Assembly[] controllerAssemblies)    {        return builder.RegisterAssemblyTypes(controllerAssemblies)            .Where(t => typeof(IController).IsAssignableFrom(t) &&                t.Name.EndsWith("Controller"));    }

The code shows that the method filters out all classes that implement the IController interface and end with a type name of "Controller". You can filter according to the actual situation of your project, and many open source sites that use AUTOFAC are doing the same.

Conclusion

Not finished, to be continued ... ^_^

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.