Autofac 依赖注入框架 使用

2015-08-02 10:20 by jiangys, 36262 阅读, 4 评论, 收藏编辑

简介

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

1
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

创建实例方法

1、InstancePerDependency

对每一个依赖或每一次调用创建一个新的唯一的实例。这也是默认的创建实例的方式。

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

2、InstancePerLifetimeScope

在一个生命周期域中,每一个依赖或调用创建一个单一的共享的实例,且每一个不同的生命周期域,实例是唯一的,不共享的。

官方文档解释: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.

3、InstancePerMatchingLifetimeScope

在一个做标识的生命周期域中,每一个依赖或调用创建一个单一的共享的实例。打了标识了的生命周期域中的子标识域中可以共享父级域中的实例。若在整个继承层次中没有找到打标识的生命周期域,则会抛出异常: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.

4、InstancePerOwned

在一个生命周期域中所拥有的实例创建的生命周期中,每一个依赖组件或调用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.

5、SingleInstance

每一次依赖组件或调用Resolve()方法都会得到一个相同的共享的实例。其实就是单例模式。

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

6、InstancePerHttpRequest

在一次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/

autoface的更多相关文章

  1. 控制反转(IOC)

    对于很多大中型项目为了实现解耦都用到了控制反转. 常用的控制反转有unity,autoface,spring.Net 使用它们的目的归根结底就一个:避免了直接new一个对象. 今天抽时间将三种控制反转 ...

  2. 游刃于MVC、WCF中的Autofac

    为了程序的健壮性.扩展性.可维护性,依赖抽象而不是具体实现类等等,于是我选择了Autofac依赖注入容器 就是这个工厂来降低耦合.之前买东西是自己去超市,现在呢 我需要什么东西,他们给送过来直接拿到了 ...

  3. Orchard源码分析(1):插件式的支持——模块和主题

    在Orchard,模块和主题都是可以插拔式的,在源码处理时,用类型(参考:DefaultExtensionTypes)区分,都没太大的本质区别,以下都称做模块. 插件的支持,实现分以下几步: 搜集模块 ...

  4. ASPNET5的依赖注入

    ASP.NET5设计的时候就是以DI为基础的,它可以利用内建的框架在Startup类的方法中,把依赖注入进去.应用服务也可以被配置的注入.默认的服务容器提供一些基本的功能,它并不打算代替现代主流的DI ...

  5. .Net IOC 之Unity

    .Net IOC 之Unity 在码农的世界里,为了应付时常变更的客户需求,增加的架构的客扩展性,减少工作量.IOC诞生了,它是一种可以实现依赖注入和控制对象生命周期的容器.最为一个有节操.有追求的码 ...

  6. .net 企业管理系统快熟搭建框架

          简言   本人在博客园注册也2年多了,一直没有写自己的博客,因为才疏学浅一直跟着园子里的大哥们学习这.net技术.一年之前跳槽到现在的公司工作,由于公司没有自己一套的开发框架,每次都要重新 ...

  7. 用Spring.Services整合 thrift0.9.2生成的wcf中间代码-复杂的架构带来简单的代码和高可维护性

    最近一直在看关于thrift的相关文章,涉及到的内容的基本都是表层的.一旦具体要用到实际的项目中的时候就会遇到各种问题了! 比如说:thrift 的服务器端载体的选择.中间代码的生成options(a ...

  8. .Net IOC 框架

    CastleWindsor 参见:CastleWindsor | .Net IOC 框架 AutoFace 参见:AutoFace | .Net IOC 框架 Unity 参见:Unity | .Ne ...

随机推荐

  1. POJ2411骨牌覆盖——状压dp

    题目:http://poj.org/problem?id=2411 状压dp.注意一下代码中标记的地方. #include<iostream> #include<cstdio> ...

  2. 【python】常用的一些内置函数

    1.cmp cmp(A,B)函数,比较A,B的大小,如果A大于B,返回1,A小于B返回-1,A等于B返回0 print cmp(12,33) >>>-1 print cmp(&quo ...

  3. 操作系统-移动操作系统-百科: iOS(苹果公司的移动操作系统)

    ylbtech-操作系统-移动操作系统-百科: iOS(苹果公司的移动操作系统) iOS是由苹果公司开发的移动操作系统.苹果公司最早于2007年1月9日的Macworld大会上公布这个系统,最初是设计 ...

  4. Django1.7开发博客

    转自: http://www.pycoding.com/articles/category/django 基于最新的django1.7写的,通俗易懂,非常适合新手入门. 感谢博主! 参考教程: htt ...

  5. shell脚本函数

    不调用就不执行 调用就执行 调用时候的$1是指执行时候的参数1 调用之后的$是位置参数

  6. php实现AES/CBC/PKCS5Padding加密解密(又叫:对称加密)

    今天在做一个和java程序接口的架接,java那边需要我这边(PHP)对传过去的值进行AES对称加密,接口返回的结果也是加密过的(就要用到解密),然后试了很多办法,也一一对应了AES的key密钥值,偏 ...

  7. SQL查询日期:

    SQL查询日期: 今天的所有数据:select * from 表名 where DateDiff(dd,datetime类型字段,getdate())=0 昨天的所有数据:select * from ...

  8. Goroutine(协程)为何能处理大并发?

    简单来说:协程十分轻量,可以在一个进程中执行有数以十万计的协程,依旧保持高性能. 进程.线程.协程的关系和区别: 进程拥有自己独立的堆和栈,既不共享堆,亦不共享栈,进程由操作系统调度. 线程拥有自己独 ...

  9. 初学 python 之 用户登录实现过程

    要求编写登录接口 : 1. 输入用户名和密码 2.认证成功后显示欢迎信息 3.用户名输错,提示用户不存在,重新输入(5次错误,提示尝试次数过多,退出程序) 4.用户名正确,密码错误,提示密码错误,重新 ...

  10. 让“懒惰” Linux 运维工程师事半功倍的 10 个关键技巧!

    好的Linux运维工程师区分在效率上.如果一位高效的Linux运维工程师能在 10 分钟内完成一件他人需要 2 个小时才能完成的任务,那么他应该受到奖励(得到更多报酬),因为他为公司节约了时间,而时间 ...