Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I dispose a service (layer)-class after I'm done using it?

So I have a service layer in my project which contains all the business logic. It is an MVC project, so when a user calls a page that requires some logic, the service class is instantiated and then used (from the controller). But it will not be used again since a new request will just instantiate a new object again.

Should I dispose these service classes after using them(using a 'using' statement? Or won't I gain any benefit from it since the garbage collector will come not much later anyway? If this is the case, the same will apply for using my repository objects I guess.

like image 574
NeedACar Avatar asked Mar 21 '23 20:03

NeedACar


1 Answers

Depends on what kind of resources your service layer are using.

A general rule of thumb:

If anything uses something which implements IDisposable then anything should either implement IDisposable or call Dispose() when done with the something

Why? Let's say that the service layer uses database connections. If you don't dispose them, they will remain open until the garbage collector collects them, leading to a lot of idle connections. That also means that the ADO.NET connection pool have to create new connections for every new HTTP request instead of reusing old ones (when the pool eventually gets empty).

Making sure that IDisposables are disposed is a cheap way of using resources efficiently.

So if you got something like this:

public class MyService
{
    public MyRepository _repos = new MyRepository();

    // [...]
}

public class MyRepository
{
    public SqlConnection _connection = new SqlConnection("...");

    // [...]
}

You should start by changing your repos to IDisposable

public class MyRepository : IDisposable
{
    public SqlConnection _connection = new SqlConnection("...");

    // [...]

    public void Dipose()
    {
        _connection.Dispose();
    }
}

Now if we want to follow the rule we either have to dispose the repository inside the methods that use the repos, or implement IDisposable in the service class too. We do the latter since we don't really now when the invoker has finished calling us (the invoker might call two methods in the service).

public class MyService : IDisposable
{
    public MyRepository _repos = new MyRepository();

    // [...]

    public void Dipose()
    {
        _repos.Dispose();
    }
}

finally we can now just do this in the controller to get everything disposed:

public ActionResult Execute()
{
    using (var service = new MyService())
    {
        service.CallA();
        service.CallB();
    }
}

I do recommend that you follow the Dispose pattern

like image 161
jgauffin Avatar answered Mar 31 '23 12:03

jgauffin