Usually all repository methods assume that a context is created. This is the most convenient way. So your FindLastID
method also shouldn't create the context, unless it's a service layer method. One simple example is to use a static variable:
public void AServiceMethod()
{
using (var context = contextProvider.CreateContext())
{
// call some domain operations, which use repositories
// commit
}
}
Where CreateContext
will open a DB session and store it in some static variable accessible from all repositories. This is not very elegant, but often is sufficient. To make it better you can use IoC as suggested by Sergey Berezovskiy. Also you may be interested in this article, recommended by Sam Leach in his answer.
Alternatively you could try something like this:
public IQueryable<Entity> GetAll()
{
return GetAll(null);
}
public IQueryable<Entity> GetAll(DBContext context)
{
if (context == null)
{
using (context = new DBContext())
{
return GetAll(context);
}
}
return context.Set<ENTITY>().Project().To<Entity>();
}
But I'd recommend the first approach, as it's simpler and easier to maintain, comprehend.