1

All,

I am writing code that looks like:

public class UserController : AuthenticatedController
{

    private MunicipalContext db = new MunicipalContext();

    // GET: Users/Edit/5
    public ActionResult Edit(int? id)
    {
        //Do stuff with db.Users
    }

    // Other action methods that do stuff with db.Users
}

Coming from a Java background, this feels like Servlets and instance fields and is starting to raise that buzzing feeling in the back of my head.

Am I going to run into thread safety issues?

3
  • No, each request will work with its own controller instance. Thread safety will only matters if you bring it into the game Commented May 18, 2017 at 22:01
  • @xxbbcc Please explain why do you think the DbContext is shared between multiple threads in this case. Commented May 18, 2017 at 22:08
  • You are, ok you could force the reuse of controller instance by configuration of the DI container, but why would you bring yourself into trouble? Commented May 18, 2017 at 22:16

2 Answers 2

5

Each controller will be created once per request, they are not singletons. No instance member is shared between threads.

So the answer is no, there is no threading issue with your code, each time a new request to an action of your UserController is made a new UserController and a new MunicipalContext are created.

A side note: remember to Dispose() your MunicipalContext instance when is no longer used. More info here.

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

2 Comments

Do you have a link to documentation where this is mentioned? I was under the impression that a separate controller is not guaranteed for every request but perhaps I'm wrong about that.
@xxbbcc The DefaultControllerFactory will create a new controller per request. This document briefly shows the lifecycle of a MVC 5 request.
1

You don't have any thread-safety issues, but typically you would use a slightly different pattern with ASP.NET MVC where the context is injected into the controller using IoC to achieve a context-per-request pattern

The problems would arise if your controller consume some services which are also doing database acccess - if you don't share the context between them you can get some odd and/or incorrect behaviour.

The IoC container can then perform the dispose on the context after the request is processed; how you actually do this depends on whether you are using traditional ASP.NET (via a HttpModule) or Owin (middleware component)

Comments

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.