1

I'm working on a project somebody else developed. In the project, it has

public class HomeController : Controller
{
    public HomeController() {
        _EntitiesContext = new EntitiesContext();
        _UsersContext = new UsersContext();
    }
    public UsersContext _UsersContext { get; set; }
    public EntitiesContext _EntitiesContext { get; set; }

    ......

Then, whenever it needs query, it will use these context.

Usually, what I do is: I do not create these context in HomeController(), instead, I create them by using .... syntax whenever I need them. I think it will open connection, do the query, then close the connection. otherwise, the connection will be always open. If too many people use it, it may generate issues.

Am I correct on this? I think I read this online before, but could not find it anymore.

Thanks

haim770
  • 48,394
  • 7
  • 105
  • 133
urlreader
  • 6,319
  • 7
  • 57
  • 91

2 Answers2

0

I think it will open connection, do the query, then close the connection.

Not quite right. ADO.NET uses a connection pool. So an actual connection to the database is not opened, it is drawn from the connection pool. And when you call Dispose on the DbContext it doesn't close the connection. It simply returns it to the pool so that it can be reused later. So don't be afraid of wrapping the DbContext instances in using statements.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

The common practice is to create one context per HTTP request, then use that same context wherever you need it.

The most viable way to achieve it is to inject the EntitiesContext dependency (traditionally using the constructor) and the most easiest way to have it injected for you with the configured object life-time is using an IoC container.

For example (using Microsoft Unity):

public HomeController(EntitiesContext context) {
    _EntitiesContext = context;
}

And container configuration (upon application initialization):

container.RegisterType<EntitiesContext>(new PerHttpRequestLifetime());
Community
  • 1
  • 1
haim770
  • 48,394
  • 7
  • 105
  • 133