Hello, I have started to look at the Entity Framework for a project I am doing and going down the road of using a BLL against it via the the repository pattern. As I understand it for each entity I should create a repository for it so I would have
public class UserRepository : IRepository<User>
{ ... }
and
public class AccountRepository : IRepository<Account>
{ ... }
With the examples I have seen it is common practice to create the entities context within a using statement and perform gets, updates and saves etc within.
using(var ctx = new AppEntities()
{
//do whatever
ctx.SaveChanges();
}
For simple access to the repository this would be ok, but what if I wanted to compose up an interaction between 2 (or more) repositories within by BLL...
public void SaveSomethingMoreComplex()
{
//BLL here stuff like validation etc
_userRepository.GetSomeData();
_accountRepository.SaveSomeData(account);
_userRepository.SaveSomeMore(user);
// Probably should have one final save that affects both repositories???
// Should be in a transaction scope also?
}
Would it be best to use the same AppEntities
instance for both repositories?
Also in this example a final save probably should be at the end of the block rather than having 2 like in my example and part of a transaction?
If I do use the same instance then is it safe to inject that in the constructor of the repositories and have it live for the lifetime of the app or is there some reason the examples I have seen tend to create and dispose within a single method call?
Thanks for any help provided.