Title: Should I Treat Entity Framework as an Unmanaged Resource?
Tags: c#;entity-framework;destructor;idisposable
Question: I am working with a class that uses a reference to EF in its constructor. 

I have implemented ```IDisposable```, but I'm not sure if I need a destructor because I'm not certain I can classify EF as an unmanaged resource. 

If EF is a managed resource, then I don't need a destructor, so I think this is a proper example:

```public ExampleClass : IDisposable
{
    public ExampleClass(string connectionStringName, ILogger log)
    {
        //...
        Db = new Entities(connectionStringName);
    }

    private bool _isDisposed;

    public void Dispose()
    {
        if (_isDisposed) return;

        Db.Dispose();

        _isDisposed= true;
    }
}
```

If EF is unmanaged, then I'll go with this:

```public ExampleClass : IDisposable
{
    public ExampleClass(string connectionStringName, ILogger log)
    {
        //...
        Db = new Entities(connectionStringName);
    }

    public void Dispose()
    {
        Dispose(true);
    }

    ~ExampleClass()
    {
        Dispose(false);
    }

    private bool _isDisposed;

    protected virtual void Dispose(bool disposing)
    {
        if (_isDisposed) return;

        // Dispose of managed resources
        if (disposing)
        {
            // Dispose of managed resources; assumption here that EF is unmanaged.
        }
        // Dispose of unmanaged resources
        Db.Dispose();

        _isDisposed = true;
        //freed, so no destructor necessary.
        GC.SuppressFinalize(this);

    }
}
```

Which one is it?

Comment: I'd consider it managed, and expect it to implement it's own finalisers for it's unmanaged parts.

Comment: Is the source code enough? https://entityframework.codeplex.com/SourceControl/latest#src/EntityFramework/DbContext.cs

Comment: I would always control the `DbContext` creation and destruction. It needs to be created for a small unit of work. Its internals follow the unit of work pattern

Comment: IDisposable does not solely deal with unmanaged resources.

Comment: Can you then explain the differences between the code? Can you explain what exactly you're asking? Is your question _"Does a DbContext have a finalizer that disposes itself"_?

Comment: It's not clear _to me_ what _you know_ about IDisposable, descructors/finalizers and (un)managed resources, hence your question is not clear _to me_ as you seem to make some shortcuts in your explanation. It's not easy to grasp someone else's train of thought. Does [How does Dispose work with Entity Framework](http://stackoverflow.com/questions/12926483/how-does-dispose-work-with-entity-framework) answer your question?

Comment: I know plenty about IDisposable and (un)managed resources, but if you want to wait for someone who can decipher your terse language, be my guest. :-)

Comment: The problem is there's no clear-cut "yes" or "no" answer to "Is DbContext unmanaged?". It's a CLR class, so it's definitely a managed object. Yet in the background it uses database connections from a pool, which tend to be (managed wrapppers for) unmanaged resources. However, the DbContext and related, internal classes by default release those unmanaged resources themselves. When you don't open connections yourself, just disposing a DbContext is enough (and often not even necessary). Nothing else to be done.

Comment: @CodeCaster I did not make that statement; neither do my examples indicate it.

Comment: @JamesBarrass - thank you. but can you point to something to prove that  to me? I'd like to rely on this going forward, if that's possible.

Comment: The second example has a destructor. If I'm dealing with only managed resources, then I don't need a destructor. Hence the title of the question. Is that more clear?

Comment: @CodeCaster It's not clear to me that you know about IDisposable based on your questions. If you cannot answer the question, please move on.

Comment: @CodeCaster No hard feelings. I would appreciate if you could point specifically to the points that are not clear, rather than stating that you don't know if I know, that I am making shortcuts, that I am terse.

Comment: @JamesBarrass - I'm not certain I'd find the answer in the source code. But I do appreciate your thoughts. I'll wait and see if someone answers it; in the meantime, I'll treat it as managed because that feels right; it feels like within EF it would deal with the unmanaged parts so I don't have to.

Comment: @CodeCaster - thank you. `However, the DbContext and related, internal classes by default release those unmanaged resources themselves.` That seems to make sense, and makes me want to treat EF as a managed resource. As I understand, I do not need a destructor for managed objects, so it appears I can use the first example with confidence until told otherwise.

Here is the accepted answer: You would never want to use a finalizer (destructor) in this case.
Whether ```DbContext``` contains unmanaged resources or not, and even whether it responsibly frees those unmanaged resources or not, is not relevant to whether you can try to invoke ```DbContext.Dispose()``` from a finalizer.
The fact is that, any time you have a managed object (which an instance of ```DbContext``` is), it is never safe to attempt to invoke any method on that instance.  The reason is that, by the time the finalizer is invoked, the ```DbContext``` object may have already been GC-collected and no longer exist.  If that were to happen, you would get a ```NullReferenceException``` when attempting to call ```Db.Dispose()```. Or, if you're lucky, and ```Db``` is still &quot;alive&quot;, the exception can also be thrown from within the ```DbContext.Dispose()``` method if it has dependencies on other objects that have since been finalized and collected.
As this &quot;Dispose Pattern&quot; MSDN article says:
```
X DO NOT access any finalizable objects in the finalizer code path, because there is significant risk that they will have already been finalized.
For example, a finalizable object A that has a reference to another finalizable object B cannot reliably use B in A’s finalizer, or vice versa. Finalizers are called in a random order (short of a weak ordering guarantee for critical finalization).
```
Also, note the following from Eric Lippert's When everything you know is wrong, part two:
```
Myth: Finalizers run in a predictable order
Suppose we have a tree of objects, all finalizable, and all on the finalizer queue. There is no requirement whatsoever that the tree be finalized from the root to the leaves, from the leaves to the root, or any other order.
Myth: An object being finalized can safely access another object.
This myth follows directly from the previous. If you have a tree of objects and you are finalizing the root, then the children are still alive — because the root is alive, because it is on the finalization queue, and so the children have a living reference — but the children may have already been finalized, and are in no particularly good state to have their methods or data accessed.
```

Something else to consider: what are you trying to dispose?  Is your concern making sure that database connections are closed in a timely fashion?  If so, then you'll be interested in what the EF documentation has to say about this:
```
By default, the context manages connections to the database. The context opens and closes connections as needed. For example, the context opens a connection to execute a query, and then closes the connection when all the result sets have been processed.
```
What this means is that, by default, connections don't need ```DbContext.Dispose()``` to be called to be closed in a timely fashion.  They are opened and closed (from a connection pool) as queries are executed.  So, though it's still a very good idea to make sure you always call ```DbContext.Dispose()``` explicitly, it's useful to know that, if you don't do it or forget for some reason, by default, this is not causing some kind of connection leak.

And finally, one last thing you may want to keep in mind, is that with the code you posted that doesn't have the finalizer, because you instantiate the ```DbContext``` inside the constructor of another class, it is actually possible that the ```DbContext.Dispose()``` method won't always get called.  It's good to be aware of this special case so you are not caught with your pants down.
For instance, suppose I adjust your code ever so slightly to allow for an exception to be thrown after the line in the constructor that instantiates the ```DbContext```:
```public ExampleClass : IDisposable
{
    public ExampleClass(string connectionStringName, ILogger log)
    {
        //...
        Db = new Entities(connectionStringName);
        
        // let's pretend I have some code that can throw an exception here.
        throw new Exception(&quot;something went wrong AFTER constructing Db&quot;);
    }

    private bool _isDisposed;

    public void Dispose()
    {
        if (_isDisposed) return;

        Db.Dispose();

        _isDisposed= true;
    }
}
```
And let's say your class is used like this:
```using (var example = new ExampleClass(&quot;connString&quot;, log))
{
    // ...
}
```
Even though this appears to be a perfectly safe and clean design, because an exception is thrown inside the constructor of ```ExampleClass``` after a new instance of ```DbContext``` has already been created, ```ExampleClass.Dispose()``` is never invoked, and by extension, ```DbContext.Dispose()``` is never invoked either on the newly created instance.
You can read more about this unfortunate situation here.
To ensure that the ```DbContext```'s ```Dispose()``` method is always invoked, no matter what happens inside the ```ExampleClass``` constructor, you would have to modify the ```ExampleClass``` class to something like this:
```public ExampleClass : IDisposable
{
    public ExampleClass(string connectionStringName, ILogger log)
    {
        bool ok = false;
        try 
        {
            //...
            Db = new Entities(connectionStringName);
            
            // let's pretend I have some code that can throw an exception here.
            throw new Exception(&quot;something went wrong AFTER constructing Db&quot;);
            
            ok = true;
        }
        finally
        {
            if (!ok)
            {
                if (Db != null)
                {
                    Db.Dispose();
                }
            }
        }
    }

    private bool _isDisposed;

    public void Dispose()
    {
        if (_isDisposed) return;

        Db.Dispose();

        _isDisposed= true;
    }
}
```
But the above is really only a concern if the constructor is doing more than just creating an instance of a ```DbContext```.

Comment for this answer: great response; thank you. however, perhaps we can flesh out a few points via comment: first, can you explain why EF is a managed object? Naively, I think of EF as a wrapper around a db connection (of course more, but that much in this context). I assume it is managed the same way I assume a class that wraps a file stream is a managed object (it's written in C# and therefore under the control of the CLR). The stream itself is opened by, perhaps Win32 dlls, I don't know, but it is not managed by the CLR. You answered my question, but you didn't tell me why EF is an unmanaged object; am I right?
Comment for this answer: second: you said `They are opened and closed (from a connection pool) as queries are executed. So, though it's still a very good idea to make sure you always call DbContext.Dispose() explicitly, it's useful to know that, if you don't do it or forget for some reason, by default, this is not causing some kind of connection leak.` and that alleviates my concern. I felt I needed to implement IDisposable on my wrapper classes, at first chiefly because I worried EF could be unmanaged. But I know that IDisposable is properly used to free both kinds of resources. So this part is appreciated as well
Comment for this answer: Finally, thank you for the bonus consideration, re: the exception in the constructor. That is a point I had not considered, and a subtlety about the pattern I had not appreciated.
Comment for this answer: great. and I understood not using a destructor for managed resources, that is why I didn't do it in my examples. But I appreciate the reminder for everyone else.
Comment for this answer: About your initial comment, it sounds like you understood the point correctly.  All .NET objects are managed and subject to garbage collection, this includes `DbContext`. In contrast, an unmanaged resource is usually something like a file handle that you need to close using low level winapi functions. You should only ever define finalizers to clear unmanaged resources, which is basically almost never.

Here is another answer: C# provides garbage collection and thus does not need an explicit destructor. If you do control an unmanaged resource, however, you will need to explicitly free that resource when you are done with it. Implicit control over this resource is provided with a Finalize( ) method (called a finalizer), which will be called by the garbage collector when your object is destroyed.

https://www.oreilly.com/library/view/programming-c/0596001177/ch04s04.html


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 15, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:08/05/15', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<c#><entity-framework><destructor><idisposable>', 'Title': 'Should I Treat Entity Framework as an Unmanaged Resource?', 'ViewCount': 2459, 'id': 31833599, 'user_AboutMe': '<p><a href="https://www.linkedin.com/profile/view?id=46338816&amp;trk=nav_responsive_tab_profile" rel="nofollow">https://www.linkedin.com/profile/view?id=46338816&amp;trk=nav_responsive_tab_profile</a></p>\n', 'user_AccountId': 3722858.0, 'user_DisplayName': 'jacoblambert', 'user_Reputation': 767.0, 'user_Views': 76.0, 'user_id': 3097458.0}}