locked
Asp.Net Web api how to create single context for each request and pass them unit of work objects RRS feed

  • Question

  • User1284890338 posted

    I'm trying to develop a web api tier. I think that I should create a ORM context(new instance of it(singleton)) for each api request and all the operations (unit of work) use the same context for that request. My first question is how to pass a context to web api constructor by using DI. The second question is how to pass the same context to all manager objects in the same request. For example, I have personController, dbContext,person, personManager, student, studentManager and so on.

    Scenario, request for personController, create dbContext for that request, use that context for student and person manager classes. As an option, all the methods inside manager classes may take the context as parameter but this brings extra cost to develop. I think I can pass that context to manager objects' constructors and they use it for all the operations.

    Friday, February 26, 2016 6:07 PM

Answers

  • User2050872319 posted

    Hi Harry US11,

    Depending on the DI container you are planning to use, the syntax could be different. But in general, it will look something like this:

    1. Set up your db context as constructor parameter for the types that require it (in your controllers, manager objects, etc)

    1. Configure your ORM context in your DI container (how to do this, depends on your ORM type)

    2. Configure your controllers, manager objects, etc in your DI container.

    3. Wire up your DI container on application startup

    In regards to the lifetime of your db context, there's a good article discussing approaching one can take: http://mehdi.me/ambient-dbcontext-in-ef6/

    Example (I am using syntax of AutoFac  container here, if other DI container is used the syntax will be different, but the logical steps will be same)

    public class MyController : Controller{
        public MyController(MyDbContext dbContext){
          .....
        }
    }
    
    public class PersonManager : IPersonManager {
       public PersonManager(MyDbContext dbContext) {
         ....
       }
    }
    
    public static class DiContainerBuilder {
    
       public static void Build(IContainer container){
             container.Register(c => new MyDbContext()).As<MyDbContext>().InstancePerRequest();
             container.RegisterType<PersonManager>().As<IPersonManager>();
       ......
       }
    }
    
    //in your Global.asax 
    ....
      DiContainerBuilder.Build(new ContainerBuilder());

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 26, 2016 6:22 PM