Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 - Controller dispose method

I am developing a MVC 5 internet application. I have the following method in my controller:

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

If I have a service class in this controller, that uses the same db object, do I need to have a Dispose() method in this service class, or does the Dispose() method in the controller take care of this?

Thanks in advance.

like image 954
user3736648 Avatar asked Dec 15 '14 11:12

user3736648


People also ask

How do I call a Dispose method?

public void Dispose() { Dispose(disposing: true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC. SuppressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time.

What is Dispose in ASP NET MVC?

The ASP.NET MVC framework calls Dispose when the request has completed processing. Developers typically do not have to call Dispose. The Dispose(Boolean) method overload is the preferred method to override.

What is Dispose () in C#?

In the context of C#, dispose is an object method invoked to execute code required for memory cleanup and release and reset unmanaged resources, such as file handles and database connections.

Can we call Dispose method in C#?

A developer can call Dispose on an instance of this class to release the memory resource held by the database connection object. After it is freed, the Finalize method can be called when the class instance needs to be released from the memory.


1 Answers

Generally: The class should dispose of any disposables it is responsible for. Responsibility essentially boils down to whether it "owns" the dependency. In other words, if it's a field on that class and that class instantiates it, then it should also dispose of it.

In the case of your service, while there's likely a field for the context on the service class, you're injecting the context into the service through the constructor, rather than having the service instantiate it. Therefore, it would not be appropriate for the service to dispose of the context, because it does not "own" it.

Further, if you were to employ a dependency injection container, such that the controller no longer instantiates the context, but rather just has it injected into its constructor, then you should also not dispose of it in the controller. The DI container would ultimately be responsible for the disposal.

like image 98
Chris Pratt Avatar answered Oct 12 '22 09:10

Chris Pratt