1

I know that one way to use a context is via the using statement.

I use it like so within my controllers

[ApiController]
public class MyController : ControllerBase
{
    [HttpPost]
    public ActionResult PostActionHere(ActionRequestClass request)
    {
        using (var context = new MyEntityFrameworkContext())
        {
         ....
         // use context here
         context.SaveChanges()
         ....
        }
    }
}

I would like to start injecting it into my controller. Mainly because I think it is easier to read and is more uniform with .NET Core dependency injection.

[ApiController]
public class MyController : ControllerBase
{
    private MyEntityFrameworkContext _myDb;

    public MyController(MyEntityFrameworkContext myDb)
    {
        _myDb = myDb;
    }

    [HttpPost]
    public ActionResult PostActionHere(ActionRequestClass request)
    {
     ....
     // use context here
     _myDb.SaveChanges()  
     ....      
    }
}

Within my startup.cs:

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyEntityFrameworkContext >(options => 

 options.UseSqlServer(Configuration.GetConnectionString("MyEntityFrameworkDatabase")));
}

What I am worried about is that injecting it I lose the disposal properties that come with the using statement. Is that true? Feel free to suggest alternate approaches.

2
  • 1
    I have never ran across a reason to manually dispose of any DbContext connections. The DbContext will automatically handle opening and closing the connection when it is needed. Commented May 24, 2019 at 21:36
  • 2
    @RugerSR9 True, but also, .Net core's DI container will take care of proper object disposal.. Commented May 24, 2019 at 21:55

1 Answer 1

2

injecting it I lose the disposal properties that come with the using statement. Is that true?

No:

The AddDbContext extension method registers DbContext types with a scoped lifetime by default.

Configuring a DbContext

And when the scope (here the HttpRequest) ends, the Scoped Lifetime object will be Disposed.

Sign up to request clarification or add additional context in comments.

2 Comments

In that article it states "However any code that explicitly executes multiple threads in paralell should ensure that DbContext instances aren't ever accesed concurrently." Does this mean that an application with asynchronous EFCore functions needs to change the scope to transient?
No. Typically you await each async call so while the DbContext might be accessed by different threads over its lifetime, it would not be accessed by multiple threads at the same time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.