I am trying to get Unity dependency injection working with a WCF service that utilises Entity Framework, but I'm getting confused about the use of context and repository.
The way I have designed it is to have a number of repository classes eg UserRepository, MessageRepository, LocationRepository, each of which accepts an EF DbContext object as a constructor parameter. This lets me control the Unit of Work at the context level, by calling context.Save() or rollback etc to control transactioning across repositories.
The confusion I'm in is that I'm not sure how to represent this in dependency injection. I want to have two scenarios
a) When the WCF service is instantiated via the WCF methods, I want it to use the DbContext class I have created and to create repository objects, passing in the created DbContext that will connect to the Entity Framework database.
b) When the WCF service methods are tested from a separate test project, I want to mock the repository objects to return mocked data.
If I was just using repository classes, this would be relatively simple as in each WCF service method I could call Container.Resolve() and then I could use the Unity WCF factory to set the concrete types for WCF instantiation, and manually configure the Unity container in my test project for the mocked types.
But the difficulty is the fact that my repositories need a DbContext class to be passed in as a constructor parameter that will survive beyond the lifetime of the repository and I also need to be able to have a reference to it in my service methods, for example
public bool CreateUser(DbUser user)
{
try
{
using (var context = new MyDbContext())
{
var repository = new UserDataRepository(context);
user.GenerateUserLight();
user.GenerateUserProfileLight();
var result = repository.InsertItem(user);
repository.Save();
return result;
}
}
catch (Exception ex)
{
return false;
}
}
How can I adapt the above method to use Unity Dependency injection so I can mock it for the test project?