autoface

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/

时间: 2024-12-29 02:35:06

autoface的相关文章

Dlib+OpenCV深度学习人脸识别

目录(?)[+] DlibOpenCV深度学习人脸识别 前言 人脸数据库导入 人脸检测 人脸识别 异常处理 Dlib+OpenCV深度学习人脸识别 前言 人脸识别在LWF(Labeled Faces in the Wild)数据集上人脸识别率现在已经99.7%以上,这个识别率确实非常高了,但是真实的环境中的准确率有多少呢?我没有这方面的数据,但是可以确信的是真实环境中的识别率并没有那么乐观.现在虽然有一些商业应用如员工人脸识别管理系统.海关身份验证系统.甚至是银行人脸识别功能,但是我们可以仔细想

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

参考页面: http://www.yuanjiaocheng.net/CSharp/csharp-class.html http://www.yuanjiaocheng.net/CSharp/csharp-variable.html http://www.yuanjiaocheng.net/CSharp/Csharp-data-types.html http://www.yuanjiaocheng.net/CSharp/cshart-value-reference-type.html http:

远距离无线通讯模块在西门子PLC无线通信中的应用方案

PLC数据通讯通常都是通过RS485有线方式进行的,如果通讯距离较远,布设通信线是非常麻烦的,为解决这个问题,采用新的应用方案:通过巨控PLC专用无线通讯模块GRM200可以实现3公里范围的PLC与电脑组态软件的无线通讯,PLC与人机界面触摸屏的无线通讯,多台PLC之间的组网远距离无线通讯,远距离传感器开关等与PLC的无线通讯. 利用巨控PLC专用无线通讯模块GRM200构建专用无线通讯连接   在很多场合,例如一个大型的监控系统,当监控点较多时,监控点与监控中心之间如果采用布线形式,投入成本高

依赖倒置原则、控制反转和依赖注入

1.依赖倒置原则: 1)上层模块不依赖与下层模块,而是共同依赖于抽象模块(或者接口). 2)抽象的东西不能是具象,具象依赖于抽象. 2.控制反转(Inversion of Control): 是软件运行时的一种行为.比如:对象A依赖于对象B,但是在B并不是直接去创建A,而是从外界取得A.就是说 一个对象并不直接去创建它所以依赖的其他对象. 3.依赖注入(Dependency Injection): 是控制反转的一个具体实现.就像上面说的一样,A的创建不是直接在B中创建,而是通过某些框架(比如Au

游刃于MVC、WCF中的Autofac

为了程序的健壮性.扩展性.可维护性,依赖抽象而不是具体实现类等等,于是我选择了Autofac依赖注入容器 就是这个工厂来降低耦合.之前买东西是自己去超市,现在呢 我需要什么东西,他们给送过来直接拿到了.  本例中将会分享 1.Autofac在Mvc的Controller控制器.Filter过滤器的使用 2.WCF中的使用 3.用Autofac来完成Unit Of Work工作单元模式 即同一个界限上下文内可以共享同一个工作单元实例.这样就可以统一提交,起到事务作用.数据统一性.一个http请求只

PLC网络的无线通信方式研究图解

PLC(可编程控制器)在工控领域应用之广,使用之方便对于稍微懂行的人来说都是不言而喻的.但是PLC的数据通信和设置都是通过RS485有线方式进行的,对于一般用户来说,PLC设备是在改造或改进项目中设计集成的,在这种情况下重新布设通信线是非常麻烦的,要打开或新挖电缆沟,这对于系统集成商来说很痛苦,增加施工难度无法保证工程进度不说,更痛苦地是有些场合根本无法布线. 在此推荐两个解决方案: 一. 利用DTD无线数据终端构建专用连接 在很多场合,例如一个大型的监控系统,当监控点较多时,监控点与监控中心之

SQL Table 自动生成Net底层-生成业务层Service

业务层接口 public static string DataTableToBaseIService(string tableName, string nameSpace, string className) { var table = SqlTableHelper.GetSQLTableInfo(tableName); StringBuilder reval = new StringBuilder(); reval.AppendFormat(@" using System; using Sys