首页 > 解决方案 > 生命周期范围是否包含对非一次性组件的引用?

问题描述

我的问题与这个问题有关Autofac 如何处理非一次性组件。医生说:

像 Autofac 这样的跟踪容器保存对它们创建的一次性组件的引用

但它并没有说 Autofac 是否持有对他们创建的非一次性组件的引用

让我们看一个具体的例子:

public class A { }  // doesn't implement IDisposable
static void Main() {
   var builder = new ContainerBuilder();

   IContainer container = builder.Build();

   using (var childScope1 = container.BeginLifetimeScope(b => { b.RegisterType<A>().InstancePerDependency(); })) {
      A a = childScope1.Resolve<A>();
      ...   // do other stuff that doesn't involve a, and let's say generation 0 has filled its budget here
      ...   
      ...   
   }
}

我的问题是:

childScope1 是否持有对 instance 的引用a,因此a在 childScope1 被处置之前不会被 GC

或者

childScope1 不包含对实例的引用,a因为A它是非一次性类,所以a可能在using块完成之前被 GCed?

标签: c#dependency-injectionautofac

解决方案


推荐阅读