I've been researching best practice for a new project when using EF (5.0 Beta Code First) as my ORM/DAL. Key considerations are testability, loosely coupled design and unit of work/transactional support across repositories.
I understand that within EF DbContext is UoW and DbSet is Repository and in a service layer you can make changes across multiple repositories co-ordinated by the DbContexts SaveChanges() method. Here's my sample configuration:
public interface IMyContext
{
IDbSet<Foo> Foos{ get; }
IDbSet<Bar> Bars { get; }
int SaveChanges();
void Dispose();
}
public class EFMyContext : DbContext, IMyContext
{
private IDbSet<Foo> _foos;
private IDbSet<Bar> _bars;
public EFMyContext()
: base("name=MyConnectionString")
{
Database.SetInitializer<EFMyContext>(null);
}
public IDbSet<Foo> Foos
{
get
{
if (_foos == null)
{
_foos = this.Set<Foo>();
}
return _foos;
}
}
public IDbSet<Bar> Bars
{
get
{
if (_bars == null)
{
_bars = this.Set<Bar>();
}
return _bars;
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new FooConfiguration());
modelBuilder.Configurations.Add(new BarConfiguration());
base.OnModelCreating(modelBuilder);
}
All fine so far. If I want to use this is an upper layer like this
public class MyService : IMyService
{
private IMyContext _context;
public MyService(IMyContext context)
{
_context = context;
}
public void DoSomethingWithMyContext()
{
// fancy implementation code
}
}
Here I run into problems as I have a direct dependency on EntityFramework.dll as MyContext exposes properties of type IDBSet. This doesn't seem right and is very similar to this question.
So my question is, how to abstract away the direct dependency on EF? I thought about introducting my own repository and unit of work to pass around a live context but how would this impact change tracking and all the other neat EF features?
The other thing I'm looking at is an IoC mechanism to manage the lifecycle of the context. Could I do away with the UoW at that point?
Sorry for the vagueness, I'm at research saturation point with this and need a definitive place to start before implementation.