Ioc:autofac lifetime scope.

During application execution, you’ll need to make use of the components you registered. You do this by resolving them from a lifetime scope.

The container itself is a lifetime scope, and you can technically just resolve things right from the container. It is not recommended to resolve from the container directly, however.

When you resolve a component, depending on the instance scope you define, a new instance of the object gets created. (Resolving a component is roughly equivalent to calling “new” to instantiate a class. That’s really, really oversimplifying it, but from an analogy perspective it’s fine.) Some components may need to be disposed (like they implement IDisposable) - Autofac can handle disposing those components for you when the lifetime scope is disposed.

However, the container lives for the lifetime of your application. If you resolve a lot of stuff directly from the container, you may end up with a lot of things hanging around waiting to be disposed. That’s not good (and you may see a “memory leak” doing that).

Instead, create a child lifetime scope from the container and resolve from that. When you’re done resolving components, dispose of the child scope and everything gets cleaned up for you.

(When you’re working with the Autofac integration libraries, this child scope creation is largely done for you so you don’t have to think about it.)

原文地址:https://www.cnblogs.com/happyframework/p/4046968.html