Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac and IDisposable interface

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)

like image 857
tugberk Avatar asked Jan 20 '12 16:01

tugberk


People also ask

Is IDisposable called automatically?

By default, the garbage collector automatically calls an object's finalizer before reclaiming its memory. However, if the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer.

What is Autofac IoC?

Autofac is an IoC container for Microsoft . 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.


1 Answers

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

like image 106
Pavel Gatilov Avatar answered Oct 27 '22 08:10

Pavel Gatilov