Autofac and IDisposable interface

强颜欢笑 提交于 2019-12-20 12:02:40

问题


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)


回答1:


Autofac calls Dispose for all instances of components implementing IDisposable 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




回答2:


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.



来源:https://stackoverflow.com/questions/8944369/autofac-and-idisposable-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!