0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much , actually this what u did , I used the unity IOC , they have a perexecutelifetimemanager , which mean to share an instance for the same request . Thank you very much .
0

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.

2 Comments

Thanks . But I have an issue . In any method I add to my repository which derive from EfRepository , use the get query instead of the context , and the get query uses the context , so how can use the dispose here .
Could you perhaps update your question with an example of what you are doing in this case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.