Instantiate Ef6.Repository

Developer
Apr 8, 2014 at 3:02 PM
Edited Apr 8, 2014 at 3:15 PM
Background
The current ctors within Ef6 are as follows:
  1. Repository: public Repository(IDataContextAsync context, IUnitOfWorkAsync unitOfWork)
  2. UnitOfWork: UnitOfWork(IDataContextAsync dataContext)
This means it is entirely possible to create a Repository with a unitOfWork parameter value that corresponds to different IDataContextAsync instance to the context parameter value. An Insert on the Repository, for example, would therefore not get committed when calling the external unitOfWork.Commit.

This is very easy to do by mistake with many of the IoC frameworks by misconfiguring the scope of a registration (e.g. InstancePer... in Autofac, but not picking on autofac in particular) and puts the onus on complex integration testing to ensure no such mistakes have crept in when building a website or other application.

Questions to ask:
  1. Is there a use-case where this makes sense: would you ever want the context and unitOfWork being injected to refer to unrelated DbContexts?
  2. How can we prevent entirely/partly the "two-context"s scenario if the answer to the previous question is no and/or yes?
Summary
Should we somehow ensure that the two items being injected through the constructor refer to the same DbContext (specifically DbContext, as this is in the Ef6 library)?

Andrew
Coordinator
Apr 9, 2014 at 5:01 PM
Answers:
  1. Potential use case: http://blog.longle.net/2013/07/30/bounded-dbcontext-with-generic-unit-of-work-generic-repositories-entity-framework-6-unity-3-0-in-mvc-4/
  2. You will need to due diligence and make sure that these DbContext are the same or different depending on your architecture use case, in this example (most general use case), we would need the DataContext to be the same for a given HttpRequest (singleton like behavior for the entire lifecycle of a user's HttpRequest), this is done with Unity using the PerRequestLifeTimeManager https://genericunitofworkandrepositories.codeplex.com/wikipage?title=ASP.NET%20MVC%205%20Controller%20Example%20with%20Async&referringTitle=Documentation.
Marked as answer by lelong37 on 4/9/2014 at 10:02 AM
Developer
Apr 9, 2014 at 5:35 PM
Le, Thanks for the response. I will review those links later this week, my current backlog is too big to look at them today.