Autofac 依賴注入框架 使用


簡介

Autofac是一款IOC框架,比較於其他的IOC框架,如Spring.NET,Unity,Castle等等所包含的,它很輕量級性能上非常高。

官方網站http://autofac.org/

源碼下載地址https://github.com/autofac/Autofac

最新版本下載可以看到,包括源碼,示例文檔,與之相關的測試項目,生成的DLL文件,其他文檔

控制反轉和依賴注入

關於控制反轉和依賴注入的文章和書籍很多,對其定義也解釋的也仁者見仁,這里就不贅述了,這是本人(只代表個人觀點)的理解:

  • 控制反轉(IoC/Inverse Of Control):   調用者不再創建被調用者的實例,由autofac框架實現(容器創建)所以稱為控制反轉。
  • 依賴注入(DI/Dependence injection) :   容器創建好實例后再注入調用者稱為依賴注入。

基本使用

安裝Autofac

Install-Package Autofac

官方使用簡單介紹:

Adding Components

Components are registered with a ContainerBuilder:

var builder = new ContainerBuilder();

Autofac can use a Linq expression, a .NET type, or a pre-built instance as a component:

builder.Register(c => new TaskController(c.Resolve<ITaskRepository>()));

builder.RegisterType<TaskController>();

builder.RegisterInstance(new TaskController());

Or, Autofac can find and register the component types in an assembly:

builder.RegisterAssemblyTypes(controllerAssembly);

Calling Build() creates a container:

var container = builder.Build();

To retrieve a component instance from a container, a service is requested. By default, components provide their concrete type as a service:

var taskController = container.Resolve<TaskController>();

To specify that the component’s service is an interface, the As() method is used at registration time:

builder.RegisterType<TaskController>().As<IController>();
// enabling
var taskController = container.Resolve<IController>();

方法一:

          var builder = new ContainerBuilder();

            builder.RegisterType<TestService>();
            builder.RegisterType<TestDao>().As<ITestDao>();

            return builder.Build();

方法二:

為了統一管理 IoC 相關的代碼,並避免在底層類庫中到處引用 Autofac 這個第三方組件,定義了一個專門用於管理需要依賴注入的接口與實現類的空接口 IDependency:

  /// <summary>
  /// 依賴注入接口,表示該接口的實現類將自動注冊到IoC容器中
  /// </summary>
  public interface IDependency
  { }

這個接口沒有任何方法,不會對系統的業務邏輯造成污染,所有需要進行依賴注入的接口,都要繼承這個空接口,例如:

業務單元操作接口:

/// <summary>
/// 業務單元操作接口
/// </summary>
public interface IUnitOfWork : IDependency
{
    ...
}

Autofac 是支持批量子類注冊的,有了 IDependency 這個基接口,我們只需要 Global 中很簡單的幾行代碼,就可以完成整個系統的依賴注入匹配:

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>));
Type baseType = typeof(IDependency);

// 獲取所有相關類庫的程序集
Assembly[] assemblies = ...

builder.RegisterAssemblyTypes(assemblies)
    .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
    .AsImplementedInterfaces().InstancePerLifetimeScope();//InstancePerLifetimeScope 保證對象生命周期基於請求
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

如此,只有站點主類庫需要引用 Autofac,而不是到處都存在着注入的相關代碼,大大降低了系統的復雜度。

參考:http://www.cnblogs.com/guomingfeng/p/osharp-layer.html

創建實例方法

1InstancePerDependency

對每一個依賴或每一次調用創建一個新的唯一的實例。這也是默認的創建實例的方式。

官方文檔解釋:Configure the component so that every dependent component or call to Resolve() gets a new, unique instance (default.)

2InstancePerLifetimeScope

在一個生命周期域中,每一個依賴或調用創建一個單一的共享的實例,且每一個不同的生命周期域,實例是唯一的,不共享的。

官方文檔解釋:Configure the component so that every dependent component or call to Resolve() within a single ILifetimeScope gets the same, shared instance. Dependent components in different lifetime scopes will get different instances.

3InstancePerMatchingLifetimeScope

在一個做標識的生命周期域中,每一個依賴或調用創建一個單一的共享的實例。打了標識了的生命周期域中的子標識域中可以共享父級域中的實例。若在整個繼承層次中沒有找到打標識的生命周期域,則會拋出異常:DependencyResolutionException

官方文檔解釋:Configure the component so that every dependent component or call to Resolve() within a ILifetimeScope tagged with any of the provided tags value gets the same, shared instance. Dependent components in lifetime scopes that are children of the tagged scope will share the parent's instance. If no appropriately tagged scope can be found in the hierarchy an DependencyResolutionException is thrown.

4InstancePerOwned

在一個生命周期域中所擁有的實例創建的生命周期中,每一個依賴組件或調用Resolve()方法創建一個單一的共享的實例,並且子生命周期域共享父生命周期域中的實例。若在繼承層級中沒有發現合適的擁有子實例的生命周期域,則拋出異常:DependencyResolutionException

官方文檔解釋:

Configure the component so that every dependent component or call to Resolve() within a ILifetimeScope created by an owned instance gets the same, shared instance. Dependent components in lifetime scopes that are children of the owned instance scope will share the parent's instance. If no appropriate owned instance scope can be found in the hierarchy an DependencyResolutionException is thrown.

5SingleInstance

每一次依賴組件或調用Resolve()方法都會得到一個相同的共享的實例。其實就是單例模式。

官方文檔解釋:Configure the component so that every dependent component or call to Resolve() gets the same, shared instance.

6InstancePerHttpRequest

在一次Http請求上下文中,共享一個組件實例。僅適用於asp.net mvc開發。

參考鏈接:

autofac 創建實例方法總結:http://www.cnblogs.com/manglu/p/4115128.html

AutoFac使用方法總結:Part I:http://niuyi.github.io/blog/2012/04/06/autofac-by-unit-test/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM