开发者

Dispose Context in EF Generic Repository

开发者 https://www.devze.com 2023-03-27 03:12 出处:网络
I have the following generic repository: public class EFRepository<TEntity, TContext> : IRepository<TEntity, TContext>,IDisposable

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.

Fe开发者_StackOverflowel free to comment about the design in general as well.


Wrap Dbcontext with UnitOfWork and inside of UnitOfWork implement dispose method.

Reference : http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/


It is completely wrong. You are creating context outside of the repository so repository cannot be responsible for the disposal. The layer where the repository is constructed for the disposal = BaseBLL must be disposable and upper layer must dispose it correctly when it doesn't need it any more.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号