Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Autofac lifetime scopes

Tags:

c#

autofac

From the documentation of Autofac, I understand that it keeps a reference to every IDisposable implementor that it creates. Therefore it can lead to OutOfMemoryException. So the suggested way to resolve dependencies is by using a ILifetimeScope.

Assume IService implements IDisposable.

class MaintenanceTask {
    private IService service;
    public MaintenanceTask(ILifetimeScope lifetimeScope) {
        service = lifetimeScope.Resolve<IService>();
    }
    //...do your work
}

But the problem with this approach is that it hides dependencies. I have to look at the code to see what that class depends on. Is there any other way to handle this in a more explicit way? More specifically, making dependencies more obvious without having to look at code? Or am I totally mistaken?

like image 615
idursun Avatar asked Dec 13 '12 12:12

idursun


People also ask

Does Autofac call Dispose?

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.

What is lifetime scope instance?

Instance Per Lifetime ScopeThis scope applies to nested lifetimes. A component with per-lifetime scope will have at most a single instance per nested lifetime scope. This is useful for objects specific to a single unit of work that may need to nest additional logical units of work.

What is Autofac C#?

Autofac is an addictive IoC container for . NET. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity. This is achieved by treating regular . NET classes as components.

How do I get Autofac containers?

From Visual Studio, you can get it via NuGet. The package name is Autofac. Alternatively, the NuGet package can be downloaded from the GitHub repository (https://github.com/autofac/Autofac/releases).


1 Answers

Passing in a lifetime scope is like passing in the container itself. It resembles the Service locator (anti-) pattern and has exactly the problem you described:
Dependecies become non-obvious.

One thing to ask yourself:
Are you actually having problems with your memory? If not, I wouldn't bother.

Another pointer:
If you have individual services that should be disposed right after usage, use a factory to create them and make your class depend on the factory instead of the service itself.

The usage scenario for lifetime scopes is a little bit different:
They are used when you need a local composition root. I never had the need for something like this in a windows application, but in web applications a Session or Request can require a local composition root.

like image 166
Daniel Hilgarth Avatar answered Sep 20 '22 03:09

Daniel Hilgarth