Instantiating the database context in the controller

1

Hello, I have a question related to the instancing mode DbContext the controller. What's the difference between the two methods below instantiation?

1.

    private ApplicationDbContext _db;
    public ApplicationDbContext db
    {
        get { return _db ?? new ApplicationDbContext(); }
        set { _db = value; }
    }

2.

private readonly ApplicationDbContext db = new ApplicationDbContext();

For now I use the second, however in several models of ASP.NET MVC 5 see that come as standard the first option ...

    
asked by anonymous 07.02.2018 / 14:21

1 answer

3

Well, the only difference I see is that in the first option if the value of _db is null it will generate a new instance, it adds a certain security to its implementation, but, as has already been commented, is just a test project, I see two problems in this:

1 - When using "new" a dependency is created between your controller and the class "ApplicationDbContext", it would be ideal to use # to reduce the coupling between the layers of your application.

2 - When querying the database directly from the controller, you are preventing it from being reused in other parts of the project, as it will only be accessible within that controller

But to cite several other problems in this approach ....

    
08.02.2018 / 04:47