Detailed description of dependency injection container autofac [go]

Source: Internet
Author: User

Detailed description of the dependency injection container autofac was published on August 1, September 22, 2011 by renfengbin Share to: Gmail mailbox Hotmail mailbox delicious Digg

The difference between autofac and other containers is that it is very closely integrated with the C # language, and has almost zero intrusion to your application during use, making it easier to integrate with third-party components, and open-source, autofac has the following main features:

1. flexible component instantiation: autofac supports automatic assembly. autofac automatically chooses to use constructor injection or attribute injection for a given component type. autofac can also create instances based on lambda expressions, this makes containers very flexible and easy to integrate with other components. 2. Resource Management visibility: the dynamic nature of applications built based on dependency injection containers means it is difficult to process those resources. Autofac uses containers to track component resource management. For objects that do not need to be cleared, such as console. Out, we call the externallyowned () method to tell the container not to clean up. Fine-grained component lifecycle management: an application usually has a container instance within the application scope, and a large number of objects within the request range exist in the application, for example, an HTTP request ends when an IIS worker thread or user session ends. Visualizes resources through nested container instances and object scopes. 3. The autofac design is very pragmatic. This is more important for the users of our containers: ● zero component intrusion: The components do not need to reference autofac. ● Flexible modular system: Through Modular Organization of your programs, applications do not need to be entangled in complicated xml configuration systems or configuration parameters. ● Automatic assembly: You can use lambda expressions to register your components. autofac will select constructors or inject attributes as needed. ● support for xml configuration files: xml configuration files are ugly during over-use, but it is usually useful for publishing.

Autofac is simple to use and added with the repository mode.

定义两个简单实体类:
public class Persion{    public string Name { get; set; }    public int Age { get; set; }}public class Custom{    public string CustomName { get; set; }    public int CustomID { get; set; }}

 

定义泛型数据库访问接口:
public interface Idal<T> where T:class{    void Insert(T entity);    void Update(T entity);    void Delete(T entity);}

 

泛型数据库访问接口的泛型实现:
public class Dal<T>:Idal<T> where T : class{    #region Idal<T> Members    public void Insert(T entity)    {        HttpContext.Current.Response.Write("您添加了一个:"           +entity.GetType().FullName);    }    public void Update(T entity)    {        HttpContext.Current.Response.Write("您更新一个:"             +entity.GetType().FullName);    }    public void Delete(T entity)    {        HttpContext.Current.Response.Write("您删除了一个:"              +entity.GetType().FullName);    }    #endregion}

 

Use the repository mode for access.

//Repository的泛型接口:public interface IRepository<T> where T:class{    void Insert(T entity);    void Update(T entity);    void Delete(T entity);} //Repository泛型接口的泛型实现:public class Repository<T>:IRepository<T> where T:class{    private Idal<T> _dal;    public Repository(Idal<T> dal)    {        _dal = dal;    }    #region IRepository<T> Members    public void Insert(T entity)    {        _dal.Insert(entity);    }    public void Update(T entity)    {        _dal.Update(entity);    }    public void Delete(T entity)    {        _dal.Delete(entity);    }    #endregion}

 

IDependency的依赖接口,不需要任何方法体,所有的业务对象都实现该接口
public interface IDependency{}

 

实现IDependency接口的CustomBll类,通过Repository模式存储数据。
public class CustomBll:IDependency{    private readonly IRepository<Custom> _repository;    public CustomBll(IRepository<Custom> repository)    {        _repository = repository;    }    public void Insert(Custom c)    {        _repository.Insert(c);    }    public void Update(Custom c)    {        _repository.Update(c);    }    public void Delete(Custom c)    {        _repository.Delete(c);    }}

 

实现IDependency接口的PersionBll类,通过Repository模式存储数据。
public class PersionBll:IDependency{    private readonly IRepository<Persion> _repository;    public PersionBll(IRepository<Persion> repository)    {        _repository = repository;    }    public void Insert(Persion p)    {        _repository.Insert(p);    }    public void Update(Persion p)    {        _repository.Update(p);    }    public void Delete(Persion p)    {        _repository.Delete(p);    }}

 

Compile the component instantiation test below

var builder = new ContainerBuilder();builder.RegisterGeneric(typeof(Dal<>)).As(typeof(Idal<>))    .InstancePerDependency();builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>))    .InstancePerDependency();builder.Register(c=>new PersionBll((IRepository<Persion>)    c.Resolve(typeof(IRepository<Persion>))));builder.Register(c => new CustomBll((IRepository<Custom>)    c.Resolve(typeof(IRepository<Custom>))));//var container = builder.Build()教程里都是使用这行代码,//我本地测试需要加入ContainerBuildOptions枚举选项。using (var container = builder.Build(ContainerBuildOptions.None))  {    // var repository= container.Resolve(typeof(IRepository<Persion>),new TypedParameter());    // IRepository<Persion> _repository = repository as Repository<Persion>;    // var m = new PersionBll(_repository);    Persion p = new Persion();    p.Name = "小人";    p.Age = 27;    var m = container.Resolve<PersionBll>();    m.Insert(p);    Custom c = new Custom();    c.CustomName = "小小";    c.CustomID = 10;    var cc = container.Resolve<CustomBll>();    cc.Update(c);}

Here, we use the containerbuilder method registergeneric to register generic classes (of course, we can also use the containerbuilder method registertype to register non-generic classes ), when the registered type is in the corresponding container, you can resolve your class instance. Builder. registergeneric (typeof (DAL <> )). as (typeof (idal <> )). instanceperdependency (); you can use as to allow the class to inject corresponding interfaces of the type through the constructor dependency. (You can also use builder. registertype <class> (). as <interface> (); to register a non-generic class) Build () method to generate a corresponding container instance, so that you can use resolve to parse the registered type instance.

Note: If you want to obtain a generic instance, you need to pass in the class represented by generic T. The Class C. Resolve (typeof (irepository <persion>) returns the object and needs to be converted to the response interface.

Of course, you can use registerassemblytypes, a new feature of autofac, to set the registration type from an Assembly according to the rules specified by the user, for example:

var builder = new ContainerBuilder();builder.RegisterGeneric(typeof(Dal<>)).As(typeof(Idal<>)).InstancePerDependency();builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerDependency();//上面的那些类如果在单独的工程里,如生成的程序集为AutofacUnitTest,就可以使用//Assembly.Load("AutofacUnitTest")获得响应的程序集。如果所有的文件在一个控制台程序里,//可以通过Assembly.GetExecutingAssembly(); 直接获得相应的程序集。Assembly dataAccess = Assembly.Load("AutofacUnitTest"); builder.RegisterAssemblyTypes(dataAccess)        .Where(t => typeof(IDependency).IsAssignableFrom(t) && t.Name.EndsWith("Bll"));//RegisterAssemblyTypes方法将实现IDependency接口并已Bll结尾的类都注册了,语法非常的简单。

 

This entry is published in the open-source category directory. Add a fixed link to favorites.

Detailed description of dependency injection container autofac [go]

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.