Autofac 和 IDisposable 接口
假设我有以下接口和类:
public interface IFooRepo : IDisposable {
//...
}
public FooRepo : IFooRepo {
//Methods here
//Properly implement the IDisposbale.Dispose() here
}
我在应用程序中使用 Autofac 作为 IoC 容器,如果我按如下方式注册它,我可以确定它会正确处理吗?
private static IContainer RegisterServices(ContainerBuilder builder) {
builder.RegisterType<FooService>().As<IFooService>();
return
builder.Build();
}
或者我应该根据我正在使用的应用程序类型采取进一步的步骤。 (在本例中,我使用 ASP.NET MVC,但我正在考虑在 WCF Web API 项目和类库中使用 autofac)
Assuming that I have the following interface and class:
public interface IFooRepo : IDisposable {
//...
}
public FooRepo : IFooRepo {
//Methods here
//Properly implement the IDisposbale.Dispose() here
}
I use Autofac as IoC container in my application and if I register this as below, can I be sure that it will disposed properly?
private static IContainer RegisterServices(ContainerBuilder builder) {
builder.RegisterType<FooService>().As<IFooService>();
return
builder.Build();
}
Or should I take further steps depending on the application type I am using. (In this case, I using ASP.NET MVC but I am considering using autofac in a WCF Web API project and a class library)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一旦其父生命周期范围结束,Autofac 就会为实现
IDisposable
的所有组件实例调用Dispose
。您不需要在这里做任何额外的工作。要熟悉 Autofac 提供的用于管理生命周期范围的选项,请点击 @dotnetstep 的链接。
管理生命周期范围是一种策略,它不仅取决于您的特定应用程序的类型(MVC 或普通 ASP.NET 或其他)。 Autofac 创建者的这篇关于生命周期的文章深入解释了话题。
对于 MVC3 项目,我建议您遵循 MVC3 集成指南。这将使所有单独的 HTTP 请求都有为其创建的单独的生命周期范围。 HTTP 请求完成后,Autofac 将完成关联的生命周期范围并处置在该范围内创建的所有一次性资源。
通过遵循相应指南
Autofac calls
Dispose
for all instances of components implementingIDisposable
once their parent lifetime scope ends. You don't need to do any additional work here.To get familiar with options provided by Autofac for managing lifetime scopes, follow @dotnetstep's links.
Managing lifetime scopes is a strategy that depends on your specific application not only its type (MVC or plain ASP.NET or whatever). This article about lifetimes by the Autofac's creator gives a deep explanation of the topic.
As for MVC3 project, I'd recommend you follow the MVC3 integration guidelines. This will make all individual HTTP requests have separate lifetime scopes created for them. Once a HTTP request is finished, Autofac will finish the associated lifetime scope and dispose all disposable resources created in that scope.
The same effect can be achieved for an ASP.NET WebForms project by following the corresponding guidelines
这部分进入 IOC 或 DI 容器的生命周期管理。
当您使用 AutoFac 时,以下链接可能会对您有所帮助。
http://autofac.readthedocs.io/en/latest/lifetime/disposal。 html
另请参阅 autofac 的“控制范围和生命周期”部分。
This portion comes into lifetime management in IOC or DI Container.
As you are using AutoFac following link may help you.
http://autofac.readthedocs.io/en/latest/lifetime/disposal.html
Also look at section of "Controlling scope and lifetime" for autofac.