Autofac垃圾收集 - BeginLifetimeScope

时间:2012-09-03 14:19:27

标签: autofac

我创建了一个用于构建和发送电子邮件的Windows服务。我已经实现了依赖注入,我使用Autofac作为DI容器。

我的问题是,当服务运行时,分配的内存不断增长,此时它已超过1GB。 I read this article about lifetimes 从这里我加入了BeginLifetimeScope,而不是直接从容器中解析。但这还没有解决问题。任何建议表示赞赏。

以下是我的服务onStart方法中的Autofac配置。

ContainerBuilder builder = new ContainerBuilder();

//Register the Database context
builder.RegisterType<DbContainer>().As<IDbContainer>();

//Register a single shared instance of Email Manager which will be shared by all EmailProcessing instances
builder.Register(c => new EmailManager()).As<IEmailManager>()).SingleInstance();

//Register email processing classes
builder.Register(c => new EmailBuilder(c.Resolve<IDbContainer>(), c.Resolve<IEmailManager>())).As<IEmailBuilder>();

_container = builder.Build();

以下是每5秒运行一次的电子邮件计时器方法。

private void EmailTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
     using (var lifetime = _container.BeginLifetimeScope())
     {
          //Builder, and any of its disposable dependencies, will
          //be disposed of when the using block completes
          IEmailBuilder builder = lifetime.Resolve<IEmailBuilder>();
          //Execute the process emails method
          builder.ProcessEmails();
     }

     emailTimer.Start();
}

我希望每个电子邮件计时器迭代都使用相同的EmailManager实例,但是其他所有内容的新实例。

修改

有没有办法检查EmailBuilder及其所有依赖项是否已经处理好并且已准备好用于GC?

我的很多物品都进入了第二代,并且正在坚持下去。生命周期结束后,他们是否应该被处置?

1 个答案:

答案 0 :(得分:2)

Autofac设置看起来很好。你确定DbContainer正在释放所有资源吗?

相关问题