Gary McGill
Gary McGill

Reputation: 27546

Why is it OK not to Dispose a UserStore

The default MVC 5 + Identity 2.1 project contains this line (in Startup.Auth.cs):

app.CreatePerOwinContext<ApplicationUserManager>ApplicationUserManager.Create);

...where the static Create method is defined (in IdentityConfig.cs) as follows:

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{
    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
     ...
}

Notice how a new UserStore<ApplicationUser> is created there, and passed to the ApplicationUserManager constructor. Note also that UserStore<T> is disposable (the base class implements IDisposable).

This struck me as odd, because I wondered who was responsible for disposing of that newly-created UserStore. I expected that ApplicationUserManager (or it's base class) must dispose of it when it itself is disposed. But no: I looked at the source and it seems not. So nobody disposes of that instance!

Why is that OK? When would you not want to dispose of an instance of a class that implements IDisposable?

Upvotes: 4

Views: 1674

Answers (2)

J Cuckaroo
J Cuckaroo

Reputation: 11

Little late but I have been creating an MVC 5 project and can confirm that Dispose on the UserStore is being called every time a http request is complete.

I believe it is coming from the IOwinContext reference when the ApplicationUserManager is created. Specifically the context being used to get the DbContext:

new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())

In the Startup class the IAppBuilder object is configured to CreatePerOwinContext:

app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

If you override the UserStore Dispose method:

protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
    }

After the base.Dispose(disposing) executes, the UserStore's Context property becomes null.

Upvotes: 1

Sam FarajpourGhamari
Sam FarajpourGhamari

Reputation: 14741

I think it is OK because UserStore is actually wrapping Entity Framework's DbContext class. And while DbContext is also Disposable but refer to this blog post disposing DbContext is not mandatory. Also it is worth pointing out that disposing injected object is not good idea in fact it is injector's responsibility to manage the object's lifetime. Therefore it is obvious UserManager dose not dispose UserStore in this case.

Upvotes: 2

Related Questions