Autofac is designed to track and dispose of resources for you.

https://autofaccn.readthedocs.io/en/latest/best-practices/

Autofac is designed to track and dispose of resources for you. To ensure this happens, make sure that long-running applications are partitioned into units of work (requests or transactions) and that services are resolved through unit of work level lifetime scopes. The per-request lifetime scope support in ASP.NET is an example of this technique.

https://autofaccn.readthedocs.io/en/latest/lifetime/disposal.html

Resources obtained within a unit of work - database connections, transactions, authenticated sessions, file handles etc. - should be disposed of when that work is complete. .NET provides the IDisposable interface to aid in this more deterministic notion of disposal.

Some IoC containers need to be told explicitly to dispose of a particular instance, through a method like ReleaseInstance(). This makes it very difficult to guarantee that the correct disposal semantics are used.

  • Switching implementations from a non-disposable to a disposable component can mean modifying client code.
  • Client code that may have ignored disposal when using shared instances will almost certainly fail to clean up when switched to non-shared instances.

Autofac solves these problems using lifetime scopes as a way of disposing of all of the components created during a unit of work.

using (var scope = container.BeginLifetimeScope()) { scope.Resolve<DisposableComponent>().DoSomething(); // Components for scope disposed here, at the // end of the 'using' statement when the scope // itself is disposed. } 

A lifetime scope is created when a unit of work begins, and when that unit of work is complete the nested container can dispose all of the instances within it that are out of scope.

Autofac and IDisposable interface

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.

扫描二维码关注公众号,回复: 5066578 查看本文章

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.

An Autofac Lifetime Primer

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

猜你喜欢

转载自www.cnblogs.com/chucklu/p/10320490.html