Wasim
Wasim

Reputation: 1935

How to dispose object context in repository pattern

I implemented a repository pattern to my application dat .

I have :

public class EFRepository<T>
{
    DbContext // My db context

    public IQureable<T> GetQuery()
    {
        DataContext.CreateQuery(...);
    }
}

Now let say I have user repository :

public class UserRepository : EFRepository { public UserGetUserDetails(int userId) { GetQuery().Where(u=>u.Id = userId).First(); } }

my problem is how to release the DbContext when I use the EF repository in derived repositories. Lets say : UserRepository: EFRepository , and it uses the GetQuery then I have to dispose the context.

Any good idea how to make this in generic repository?

Upvotes: 0

Views: 2121

Answers (2)

VladT
VladT

Reputation: 360

You should think about what unit of work you have. (there are many other tutorials on the internet). The idea is to keep the same dbcontext and to re-use it while being in the same unit of work. This way, entities will already be attached to the context when needing them, etc..

Now, this being a web application, your unit of work would be in this case a request. While in the same request, reuse your DBContext. There are many ways to do this and just off the top of my head - you will want something like 'OnActionExecuting' where you take care of your context.

But even better would be to use an Inversion of Control pattern (there are many frameworks out there that use this, i primarily use NInject . This will automatically create a new instance of a certain class, when needed, depending on the scope you suggested - in this case 'onRequestScope'. A lot more to say about IoC but not the scope of the question

Upvotes: 1

nick_w
nick_w

Reputation: 14938

I have used a similar pattern in the past and in my case I actually inherited from DbContext, which itself implements IDisposable. Provided you are using EFRepository or classes derived from it in a using block you should be fine.

If you would prefer a DbContext member variable, then EFRepository will need to implement IDisposable and call DbContext.Dispose() from its Dispose method.

Upvotes: 0

Related Questions