Instantiating the database context in the controller

Asked

Viewed 119 times

1

Hello, I have a question related to the Dbcontext instantiation mode in the controller. What is 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();

Because currently I use the second, but in several models of ASP.NET MVC 5 I see that comes as standard the first option...

  • In fact if you instance like this is already wrong the two ways ... !!! in the functional sense the two work the same way and brings what you need.

1 answer

2


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, adds a certain security to its implementation, but, as it was already commented, unless this is just a test project, I see two problems in that:

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

2 - By performing database queries 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 we can cite several other problems in this approach....

  • First of all, thank you for the answer and the quote about addiction injection. But from what I understood in this subject, I would have to pass the context (Applicationdbcontext) via constructor (obeying the Dependency Injection) on all actions that would use the class "Applicationdbcontext" and at what moment I urge the same? Because the way I see it, in the Controller and Actions situation, I don’t think it’s feasible to use this architecture...

  • Well, dependency injection has its advantages in reducing coupling and facilitating code maintenance, since the modifications you make will not impact other areas of your project, but it is somewhat more laborious, requires other configurations, so while it’s good practice, depending on the size and complexity of your project, it won’t be worth it. "which moment do I urge the same?" Actually you don’t instance, the instance is "injected" for you at runtime via constructor, ie there is a new one underneath the cloths.

  • I understood, and from what I saw, you have to use some tools to instantiate the class in the constructor when you initialize the application in Startup.Cs, well I will research further by sinking here, but I intend to make this application for large scale

Browser other questions tagged

You are not signed in. Login or sign up in order to post.