说明:本文是对参考文章的一个整理,做一个记录,基本没有翻译,详情请参看原文.

使用注意要点:

Autofac will track every disposable component instance that it creates, no matter how that instance is requested.

Don’t resolve from the root container. Always resolve from and then release a lifetime scope.

不推荐、不宜的用法:

一、

interface IMyResource { … }

class MyResource : IMyResource, IDisposable { … }

When an instance of MyResource is created in an Autofac container, the container will hold a reference to it even when it is no longer being used by the rest of the program. This means that the garbage collector will be unable to reclaim the memory held by that component, so the following program will eventually exhaust all available memory and crash
var builder = new ContainerBuilder();
builder.RegisterType<MyResource>().As<IMyResource>();
using (var container = builder.Build())
{
while (true)
var r = container.Resolve<IMyResource>(); // Out of memory!
}
his is a far cry from typical CLR behaviour, which is one more reason why it is good to get away from thinking about an IoC container as a replacement for new. If we’d just created MyResource directly in the loop, there wouldn’t be any problem at all
while (true)
var r = new MyResource(); // Fine, feed the GC

二、

interface IMyService { }

class MyComponent : IMyService
{
// Dependency on a service provided by a disposable component
public MyComponent(IMyResource resource) { … }
} If a second component is resolved that depends on a service provided by a disposable component, the memory leak still occurs
while (true)
// Still holds instances of MyResource
var s = container.Resolve<IMyService>();

三、

interface IMyService2
{
void Go();
} class MyComponent2 : IMyService2
{
Func<IMyResource> _resourceFactory; public MyComponent(Func<IMyResource> resourceFactory)
{
_resourceFactory = resourceFactory;
} public void Go()
{
while (true)
var r = _resourceFactory(); // Still out of memory.
}
}

有什么方式可以改善上面的情况呢?

答:lifetime Scopes

// var container = …
while (true)
{
using (var lifetimeScope = container.BeginLifetimeScope())
{
var r = lifetimeScope.Resolve<IMyResource>();
// r, all of its dependencies and any other components
// created indirectly will be released here
}
}

Lifetime Scopes 可以被嵌套使用:

var ls1 = container.BeginLifetimeScope();
var ls2 = ls1.BeginLifetimeScope();
// ls1 is a child of the container, ls2 is a child of ls1

Lifetime Scopes 不会产生上下文依赖:

var ls1 = container.BeginLifetimeScope();
var ls2 = container.BeginLifetimeScope();
// ls1 and ls2 are completely independent of each other

Owned Instance:

Owned instances (Owned<T>) are the last tale in Autofac’s lifetime story.

An owned instance is a component that comes wrapped in its own lifetime scope. This makes it easier to keep track of how a component should be released, especially if it is used outside of a using statement.

To get an owned instance providing service T, you can resolve one directly from the container

var ownedService = container.Resolve<Owned<IMyService>>();

In lifetime terms, this is equivalent to creating a new lifetime scope from the container, and resolving IMyService from that. The only difference is that the IMyService and the lifetime scope that holds it come wrapped up together in a single object.

The service implementation is available through the Value property:

// Value is IMyService
ownedService.Value.DoSomething();

When the owned instance is no longer needed, it and all of its disposable dependencies can be released by disposing the Owned<T> object:

ownedService.Dispose();

Owner Instance 与 Fun 结合使用:

Components that are returned from Func<T> delegates are associated with the same lifetime scope as the delegate itself. If that component is itself contained in a lifetime scope, and it creates a finite number of instances through the delegate, then there’s no problem – everything will be cleaned up when the scope completes.

If the component calling the delegate is a long-lived one, then the instances returned from the delegate will need to be cleaned up eagerly. To do this, Owned<T> can be used as the return value of a factory delegate

class MyComponent2 : IMyService2
{
Func<Owned<IMyResource>> _resourceFactory; public MyComponent(Func<Owned<IMyResource>> resourceFactory)
{
_resourceFactory = resourceFactory;
} public void Go()
{
while (true)
using (var r = _resourceFactory())
// Use r.Value before disposing it
}
} Func<T> and Owned<T> can be combined with other relationship types to define relationships with a clearer intent than just taking a dependency on ILifetimeScope

参考文章:

http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/

http://nblumhardt.com/2010/01/the-relationship-zoo/

关于Autofac的使用陷阱的更多相关文章

  1. 深入理解Autofac生命周期

    为什么Autofac表现的这样? 这里似乎有几个陷阱,虽然这里只有一个------并且这个值得重申: Autofac将会跟踪每一个他所创建的可销毁的组件实例,无论这个实例是怎样被获取的. 当然,最终. ...

  2. Autofac容器对象实例的几种生命周期类型

    实例范围决定了如何在同一服务的请求之间共享实例. 请注意,您应该熟悉生命周期范围的概念,以便更好地理解此处发生的情况. 当请求服务时,Autofac可以返回单个实例(单实例作用域),新实例(每个依赖作 ...

  3. .NET手记-为ASP.NET MVC程序集成Autofac

    MVC Autofac总是会紧跟最新版本的ASP.NET MVC框架,所以文档也会一直保持更新.一般来讲,不同版本的框架集成Autofac的方法一般不变. MVC集成需要引用 Autofac.Mvc5 ...

  4. autofac生命周期入门(如何避免内存泄漏)

    如果你是一个IOC新手,那么生命周期可能会比较难以理解.以至于谈到这个问题时,一些老手也时常表示疑虑和害怕.一个令人不安的问题就是-对象没有在合适的时机被销毁.这样一来内存的使用率就会一直攀升,直到程 ...

  5. AutoFac在项目中的应用

    技能大全:http://www.cnblogs.com/dunitian/p/4822808.html#skill 完整Demo:https://github.com/dunitian/LoTCode ...

  6. Autofac - MVC/WebApi中的应用

    Autofac前面写了那么多篇, 其实就是为了今天这一篇, Autofac在MVC和WebApi中的应用. 一.目录结构 先看一下我的目录结构吧, 搭了个非常简单的架构, IOC(web), IBLL ...

  7. Autofac - 生命周期

    实例生命周期决定在同一个服务的每个请求的实例是如何共享的. 当请求一个服务的时候,Autofac会返回一个单例 (single instance作用域), 一个新的对象 (per lifetime作用 ...

  8. Autofac - 属性注入

    属性注入不同于通过构造函数方式传入参数. 这里是通过注入的方式, 在类创建完毕之后, 资源释放之前, 给属性赋值. 这里, 我重新弄一些类来演示这一篇吧. public class ClassA { ...

  9. Autofac 的点滴

    泛型类型的注册和使用 public interface IRepository<T> where T:class { } public interface ISchoolDetailRep ...

随机推荐

  1. 【全国互虐】Fibonacci矩阵

    orz啊又被屠了 人生如此艰难 题意: 给定一个k维的n^k的超立方体 超立方体的元素Ai1,i2,...,ik 的值为f(i1+i2+...+ik-k+1) f为斐波那契数列 求该超立方体的所有元素 ...

  2. 'System.Web.Http.GlobalConfiguration' does not contain a definition for 'Configure'

    It needs the system.web.http.webhost which is part of this package. I fixed this by installing the f ...

  3. 2010“架构师接龙”问答--杨卫华VS赵劼(转)

    add by zhj:虽然是几年前的文章,但还是很有参考价值的 原文:http://blog.zhaojie.me/2010/05/programmer-magazine-2010-5-archite ...

  4. Swift 可选值(Optional Values)介绍

    Optional的定义 Optional也是Objective-C没有的数据类型,是苹果引入到Swift语言中的全新类型,它的特点就和它的名字一样:可以有值,也可以没有值,当它没有值时,就是nil.此 ...

  5. Rdlc报表出现空白页解决方法

    在使用RDLC报表时,碰到这种情况:当只有一页数据时,报表确显示两页,第二页除了报表头之外数据为空.然后,当有多页数据时,最后一页为空. RDLC報表設計好後,在ReportViewer預覽報表時,頁 ...

  6. hdu 1045 Fire Net(最小覆盖点+构图(缩点))

    http://acm.hdu.edu.cn/showproblem.php?pid=1045 Fire Net Time Limit:1000MS     Memory Limit:32768KB   ...

  7. 关于“未使用GUID分区表”无法安装的解决方案

    原帖链接:http://itc.do-johodai.ac.jp/~s0823612/ 原版的Mac不能安装在mbr分区.必须得用GUID分区,其实装在mbr也可以,需要修改两个文件一个是OSInst ...

  8. 技术文集:万能WINDOWS XP封装

    这里将系统封装分为3步:做系统.封装.部署 一.做系统 平台不限,但不建议在虚拟机上制作.CPU及主板芯片没有限制,关于intelide和intelppm的不兼容问题,深度白金3in1并没有删除这些注 ...

  9. mysql慢查询Slow Query Log和未使用索引(Not Using Indexes)查询配置和使用

    mysql的“慢查询”指的是超过了允许的最大查询时间(long_query_time)的sql语句,而“未使用索引”查询顾名思义就是查询语句没有使用到索引的sql语句. 慢查询配置和使用 在msyql ...

  10. CodeForces 534B Covered Path (水题)

    题意:给定两个速度,一个一初速度,一个末速度,然后给定 t 秒时间,还每秒速度最多变化多少,让你求最长距离. 析:其实这个题很水的,看一遍就知道怎么做了,很明显就是先从末速度开始算起,然后倒着推. 代 ...