user4410678
user4410678

Reputation:

Repository as static or non-static class?

Recently I had a discussion with a colleague on whether a repository in a web application (in this case a layer on top of Entity Framework) should be implemented as static or non-static classes.

In this question I'm not interested if one or the other implementation is a better (OOP) design, because that would make the answers subjective.

What I am interested in: Is instantiating and disposing the Entity Framework DbContext handled in a different way in the CLR when you compare the static with the non-static class? I am specifically interested in multi-threading issues and memory usage, because this code runs in an MVC web application.

Edit: Just to clarify: I'm not interested in the disposal or garbage collection of the repository class, just what happens with the local context variable. Is it correct to say that it is carbage collected (or at least marked to be garbage collected) when the method returns?

Static repository

public static class AccountRepository
{
    public static AccountModel GetAccountById(int accountId)
    {
        using (var context = new EntitiesContext())
        {
            var account = context.Accounts.FirstOrDefault(a => a.Id == accountId);
            if (account == null)
            {
                return null;
            }

            return new AccountModel
            {
                Id = account.Id,
                Username = account.Username,
                // etc...
            };
        }
    }
}

Non-static repository

public class AccountRepository
{
    public AccountModel GetAccountById(int accountId)
    {
        using (var context = new EntitiesContext())
        {
            var account = context.Accounts.FirstOrDefault(a => a.Id == accountId);
            if (account == null)
            {
                return null;
            }

            return new AccountModel
            {
                Id = account.Id,
                Username = account.Username,
                // etc...
            };
        }
    }
}

Upvotes: 8

Views: 4132

Answers (1)

bstenzel
bstenzel

Reputation: 1241

The only difference between the call of a static method and an instance method is that static methods use one less parameter: the this reference which is passed to instance methods. And since the DbContext is stored in a local variable in both cases, it's free to be garbage-collected when the method terminates either way. No difference there.

That's still no excuse to use a static repository IMHO. Good vs better design may be subjective. Good vs bad design is not. SoC and SRP aren't either.

Upvotes: 4

Related Questions