DatabaseFactory and MyFinanceContext

Aug 27, 2014 at 7:47 AM
Hi,

I was wondering whether DatabaseFactory would return the same MyFinanceContext to all methods that call it. I do not have any prior experience with UnityContainer or (IoC in general), so I was not sure whether DatabaseFactory returns a new instance or the same instance all the time.

My primary concern is what would happen if 2 requests were to come in at the same time. Would both requests be accessing the same MyFinanceContext object? If they are accessing the same MyFinanceContext object, then a lot can go wrong whenever one of them performs SaveChanges().

My secondary concern is with DataContext dispose method. According to guidelines specified here (http://msdn.microsoft.com/en-us/data/jj729737), it says with long running context, "The chances of concurrency-related issues increase as the gap between the time when the data is queried and updated grows." This goes back to my understanding that DatabaseFactory will be returning the same MyFinanceContext on each Get() call.

Please share your opinion on this issue.

Thanks.
Aug 29, 2014 at 12:07 AM
After doing hours of research on how the ASP.NET MVC Controllers and ASP.NET Web API Controllers are constructed, I realized the Database Factory will NEVER return the same MyFinanceContext to 2 different requests.

Key things I learned:
  1. Controllers are created for each request for both MVC and Web API. (Source: http://stackoverflow.com/questions/16647969/asp-net-mvc-request-life-cycle and http://www.asp.net/web-api/overview/advanced/dependency-injection).
  2. Dependency Injection is used in constructing both the repository class as well as the controller class.
  3. You have to set up Dependency Injection differently for MVC and Web API.
    a. MVC uses IControllerFactory to create Controllers. DI can be best used at that point! (Tutorial: http://www.codeproject.com/Articles/99361/How-To-Use-Unity-Container-In-ASP-NET-MVC-Framewor)
    b. WebApi uses IDependencyResolver to create Controllers. DI can be used at that point! (Tutorial: http://www.asp.net/web-api/overview/advanced/dependency-injection)
I hope someone finds these learnings useful.
Marked as answer by parthsha on 8/28/2014 at 5:08 PM