0

In a controller, is there any difference between declaring a database context instance like this:

public class MyController : Controller
{
    private readonly MyDatabaseEntities _context = new MyDatabaseEntities();

    public ActionResult Index()
    {
        ...
    }
}

Versus this:

public class MyController : Controller
{
    private readonly MyDatabaseEntities _context;

    public MyController()
    {
        _context = new MyDatabaseEntities();
    }

    public ActionResult Index()
    {
        ...
    }
}

I'm just beginning to realise that the way I've been handling database context in my ASP.NET apps may not have been correct (or at least ideal) for a while and I'm reading up on it and thinking of how I'm going to start using Dependency Injection, but for starters I was just wondering if I'm even instantiating database contexts in my controllers correctly.

Incidentally, I'm still working in .NET Framework 4.7.2. Hopefully we'll start working in .NET 5 soon!

Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
Philip Stratford
  • 4,513
  • 4
  • 45
  • 71
  • 1
    Yes, there is difference but you can see it only in IL. check this answer https://stackoverflow.com/a/54446564/5405449 – Irakli Gabisonia Nov 11 '20 at 16:24
  • 1
    @IrakliGabisonia Is correct; field initialisers run before the constructor, but logically your examples are identical. If your moving to DI, you will need to declare `MyDatabaseEntities` as a dependency via your constructor. – Johnathan Barclay Nov 11 '20 at 16:31

0 Answers0