AutoFac IoC DI dependency injection, autofacioc

Source: Internet
Author: User

AutoFac IoC DI dependency injection, autofacioc
Record little bit by bit knowledge, in order to better serve the future! I. Why is AutoFac used?

I have introduced two IOC containers, Unity and Ninject, but I found that AutoFac is more common in the garden. So I spent two days and found that this is indeed a tall IOC container ~

Autofac is one of the most popular IOC frameworks in the. NET field. It is said that it is the fastest:

Advantages:

  • It is closely related to the C # language. That is to say, many programming methods in C # Can Be Used for Autofac. For example, you can use Lambda expressions to register components.
  • Low learning curve, learning it is very simple, as long as you understand the concept of IoC and DI and when to use them
  • XML configuration support
  • Automatic Assembly
  • Integration with Asp. Net MVC 3
  • Microsoft's Orchad open-source program uses Autofac. It can be seen from the source code that it is convenient and powerful.

Since it is so cool, we take it for granted, so we recommend it as the ultimate solution of IOC!

Ii. Use of AutoFac

First, you must obtain AutoFac. Here you can load it in various ways. Here I still load AutoFac through NuGet in VS. Either way, the ultimate goal is to convert Autofac. dll, Autofac. configuration. dll these two assembly references to your project. In this way, if you want to use AutoFac in your project, you only need to add its namespace reference ~

1. AutoFac entry

First, we define a data access interface:

public interface IDAL{    void Insert(string commandText);}

Then we use the SQL and Oracle methods to implement the above interfaces respectively. However, this is just a demonstration, so we didn't actually implement these two classes. You know ~

SQL method:

Public class SqlDAL: IDAL {public void Insert (string commandText) {Console. WriteLine ("add related information using sqlDAL ");}}

Oracle:

Public class incluledal: IDAL {public void Insert (string commandText) {Console. WriteLine ("add related information using incluledal ");}}

Then inject constructor injection:

public class DBManager {     IDAL _dal;    public DBManager(IDAL dal)     {         _dal= dal;    }public void Add(string commandText)     {         _dal.Insert(commandText);     }}

Finally, to truly complete dependency injection, AtuoFac will be launched:

var builder = new ContainerBuilder(); builder.RegisterType<DBManager>(); builder.RegisterType<SqlDAL>().As<IDAL>(); using (var container = builder.Build()) {     var manager = container.Resolve<DBManager>();     manager.Add("INSERT INTO Persons VALUES ('Man', '25', 'WangW', 'Shanghai')"); }

From the preceding examples, we can see that the use of AutoFac is a bit like that of Unity. The key thing is the Container class.

2. Description of common AutoFac methods (1) builder. RegisterType < Object> (). As < Iobject> (): The registration type and its instance. For example, the following is the instance SqlDAL that registers the interface IDAL.
ContainerBuilder builder = new ContainerBuilder();builder.RegisterType<SqlDAL>().As<IDAL>();IContainer container = builder.Build();SqlDAL sqlDAL = (SqlDAL)container.Resolve<IDAL>();
(2) IContainer. Resolve <IDAL> (): resolves the instance of an interface. For example, the last line of code above is to parse the IDAL instance SqlDAL (3) builder. RegisterType < Object> (). Named < Iobject> (String name): registers different instances for an interface. Sometimes it is inevitable that multiple classes map to the same interface. For example, SqlDAL and OracleDAL both implement the IDAL interface. In order to accurately obtain the desired type, you must name it at registration.
builder.RegisterType<SqlDAL>().Named<IDAL>("sql");builder.RegisterType<OracleDAL>().Named<IDAL>("oracle");IContainer container = builder.Build();SqlDAL sqlDAL = (SqlDAL)container.ResolveNamed<IDAL>("sql");OracleDAL oracleDAL = (OracleDAL)container.ResolveNamed<IDAL>("oracle");
(4) IContainer. ResolveNamed <IDAL> (string name): resolves the "named instance" of an interface ". For example, the last line of code above is to parse the IDAL named instance OracleDAL (5) builder. RegisterType < Object> (). Keyed < Iobject> (Enum enum): registers different instances for an interface by enumeration. Sometimes we use enumeration to differentiate different implementations of an interface, rather than strings. For example:
public enum DBType{ Sql, Oracle}
builder.RegisterType<SqlDAL>().Keyed<IDAL>(DBType.Sql);builder.RegisterType<OracleDAL>().Keyed<IDAL>(DBType.Oracle);IContainer container = builder.Build();SqlDAL sqlDAL = (SqlDAL)container.ResolveKeyed<IDAL>(DBType.Sql);OracleDAL oracleDAL = (OracleDAL)container.ResolveKeyed<IDAL>(DBType.Oracle);
(6) IContainer. ResolveKeyed <IDAL> (Enum enum): parses a specific instance of an interface based on the enumerated value. For example, the last line of code above is to parse the specific IDAL instance OracleDAL (7) builder. registerType <Worker> (). instancePerDependency (): used to control the lifecycle of objects. Each time an instance is loaded, a new instance is created. The default setting is this method (8) builder. registerType <Worker> (). singleInstance (): used to control the object lifecycle. The same instance (9) IContainer is returned each time an instance is loaded. resolve <T> (NamedParameter namedParameter): assign a value to the instance T when parsing it
DBManager manager = container.Resolve<DBManager>(new NamedParameter("name", "SQL"));
public class DBManager {       IDAL dal;    public DBManager (string name,IDAL  _dal)    {        Name = name;        dal= _dal;    }}
3. Use AutoFac (1) to configure the configuration file first.
<?xml version="1.0"?>  <configuration>    <configSections>      <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/>    </configSections>    <autofac defaultAssembly="ConsoleApplication1">      <components>        <component type="ConsoleApplication1.SqlDAL, ConsoleApplication1" service="ConsoleApplication1.IDAL" />      </components>    </autofac>  </configuration>
(2) read Configuration to implement dependency injection (note the introduction of Autofac. Configuration. dll)
static void Main(string[] args)    {        ContainerBuilder builder = new ContainerBuilder();        builder.RegisterType<DBManager>();        builder.RegisterModule(new ConfigurationSettingsReader("autofac"));        using (IContainer container = builder.Build())        {            DBManager manager = container.Resolve<DBManager>();            manager.Add("INSERT INTO Persons VALUES ('Man', '25', 'WangW', 'Shanghai')");     } 
Iii. ASP. net mvc and AtuoFac

Finally, it's time to combine ASP. net mvc and AtuoFac. Let's take a look at the application of AtuoFac in MVC. In fact, it's very simple. There are several steps to do it:

1. First register your controller class in the Application_Start () function. You must introduce Autofac. Integration. Mvc. dll
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Http;using System.Web.Mvc;using System.Web.Optimization;using System.Web.Routing;using Autofac;using AtuoFacOfMVC4.Models;using System.Reflection;using Autofac.Integration.Mvc;namespace AtuoFacOfMVC4{   public class MvcApplication : System.Web.HttpApplication    {        protected void Application_Start()        {            var builder = new ContainerBuilder();            SetupResolveRules(builder);            builder.RegisterControllers(Assembly.GetExecutingAssembly());            var container = builder.Build();            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));            AreaRegistration.RegisterAllAreas();            WebApiConfig.Register(GlobalConfiguration.Configuration);            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);            RouteConfig.RegisterRoutes(RouteTable.Routes);            BundleConfig.RegisterBundles(BundleTable.Bundles);            AuthConfig.RegisterAuth();        }        private void SetupResolveRules(ContainerBuilder builder)        {            builder.RegisterType<StudentRepository>().As<IStudentRepository>();        }    }}
2. Inject dependency code into your MVC program. (1) declare a Student class.
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace AtuoFacOfMVC4.Models{    public class Student    {        public int Id { get; set; }        public string Name { get; set; }        public string Graduation { get; set; }        public string School { get; set; }        public string Major { get; set; }    }}
(2) Declare the warehousing interface and its implementation
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace AtuoFacOfMVC4.Models{    public interface IStudentRepository    {        IEnumerable<Student> GetAll();        Student Get(int id);        Student Add(Student item);        bool Update(Student item);        bool Delete(int id);    }}
View Code (3) Add the Controller StudentController and inject the dependent Code
Using System; using System. collections. generic; using System. linq; using System. web; using System. web. mvc; using AtuoFacOfMVC4.Models; namespace usage {public class StudentController: Controller {readonly IStudentRepository repository; // The constructor injects public StudentController (IStudentRepository repository. repository = repository;} public ActionResult Index () {var data = repository. getAll (); return View (data );}}}
(4) Add a View to the Index method of the controller StudentController. The running effect is as follows:

 

* By recording and sharing your learning records, you can grow yourself and help others occasionally. Why not? If this article is useful to you, I 'd like to recommend it for you ~

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.