0

I developed an ASP.NET MVC application with EntityFramework and I'd like to know that is it best practices to implement Singleton Pattern for DbContext in the project?

Here is my code:

private static Lazy<DbContext> _instance = new Lazy<DbContext>(()
    => new DbContext());

public static DbContext Instance
{
    get
    {
        if (
            _instance.Value.Database.Connection.State == 
            System.Data.ConnectionState.Closed
           )
            _instance.Value.Database.Connection.Open();

        return _instance.Value;
    }
}

Because of the connection state which closes after each connecting to the database, Before returning the DbContext instance, I've checked the connection state and open it if that isn't open.

Actually, I'm not sure about the implemented pattern for the DbContext and I would like to know if there is a better way to implement Singleton when we're working with DbContext? Should we use Singleton for DbContext at all?

AhmadReza Payan
  • 2,171
  • 1
  • 23
  • 33

1 Answers1

2

If you are developing a CRUD type application then investigate the generic repository pattern as described here: http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle

Notice that the context is a private instance variable.

w0051977
  • 15,099
  • 32
  • 152
  • 329