Miguel Moura
Miguel Moura

Reputation: 39524

Moving away from Repository pattern. How should I use DBContext?

On an MVC / Entity Framework project I am moving away from the Repository pattern.

First, it has given me a few problemas ... And I think DBContext and IDBset kind of implement UnitOfWork and Repository.

So I am starting to use commands and queries. Here is an example:

public class ListPostsQuery {

  public ListPostsQuery() {
  }

  public List<Post> Execute(int currentPage, int pageSize) {

  }
}

How should I integrate or inject DBContext in my Queries / Commands?

Maybe using a wrapper for DBContext with Save method and exposing the sets?

Or should I just create a new context in Execute method?

  public List<Post> Execute(int currentPage, int pageSize) {

    using (Context = new DBContext) {
    }

  }

Could someone, please, advice me on this?

Upvotes: 1

Views: 305

Answers (2)

Wiktor Zychla
Wiktor Zychla

Reputation: 48314

Use constructor injection, i.e. pass your context to service classes via constructor.

public class ListPostsQuery {

  private DbContext ctx;

  public ListPostsQuery( DbContext ctx ) {
     this.ctx = ctx;
  }

  public List<Post> Execute(int currentPage, int pageSize) {

     return ctx....

  }
}

This way you control the lifetime of your context once, e.g. in a controller factory or using an ioc framework of your choice.

Upvotes: 3

Alex Art.
Alex Art.

Reputation: 8781

I would stick with

using (Context = new DBContext) 
{
}

The reason is that Context is not thread safe so if you will try to do things concurrently using the same context it could cause some really bad issues with your data.

Regarding the dependency injection: It is certainly great pattern but what is your profit of using it here? - you are still tightly coupled to the Context... - you won't be able to test your classes by injecting stub context...

Upvotes: 2

Related Questions