I have the following generic repository:
public class EFRepository<TEntity, TContext> : IRepository<TEntity, TContext>, IDisposable
where TEntity : class
where TContext : ObjectContext
{
protected TContext context;
public EFRepository(TContext context)
{
this.context = context;
}
//CRUD methods...
public void Dispose()
{
if (null != context)
{
context.Dispose();
}
}
}
This is a class from the Business layer
public class UserBLL : BaseBLL<User>
{
EFRepository<User, MyEntities> userRepo = null;
public UserBLL() : base ()
{
//Context is created in the consructor of the base class and passed to repository
userRepo = new EFRepository<User, MyEntities>(Context);
}
}
Here is the base business class:
public class BaseBLL <TEntity>
where TEntity : class
{
protected MyEntities Context { get; set; }
public BaseBLL()
{
this.Context = DataAccessHelper.Context;
this.Context.MetadataWorkspace.LoadFromAssembly(typeof(TEntity).Assembly);
}
}
In this design, since I'm creating an instance of the repository in the business class constructor rather than inside a using clause, the dispose method of the repository is not getting called by default. My main question is how to make sure the context/repository is disposed.
I know I can create the repository in a using clause inside each method rather than in the constructor, but I wonder if there's a more elegant way.
Feel free to comment about the design in general as well.