user1476207
user1476207

Reputation: 377

MVC db context overuse?

I have added a database repository layer to my MVC application which does the CRUD. Sometimes my controllers need to call multiple db repositories and I do this by calling the db respitories I need. This in turn creates multiple db context objects. One for each repository. Should there be multiple db context objects or should I pass in a single db context to the repository object?

Upvotes: 0

Views: 916

Answers (2)

Soroush Mirzaei
Soroush Mirzaei

Reputation: 926

There should be only one, I highly recommend using Unit of Work pattern:

Here's a quick and simple example:

public interface IUoW : IDisposable
{
    MyDbContext DbContext { get; set; }  

    void SaveChanges();
}

public class UoW : IUoW
{
    public MyDbContext DbContext { get; set; }

    public UoW()
    {
        DbContext = new MyDbContext();
    }

    public void SaveChanges()
    {
        DbContext.SaveChanges();
    }

    public void Dispose()
    {
        DbContext.Dispose();
    }
}

You need to instantiate UoW once for each request and pass it to your repository:

public class MyRepository
{
    private MyDbContext _context;

    public MyRepository(IUoW uow)
    {
        _context = uow.MyDbContext;
    }

    // your crud methods
}

Of course it's just a very simple example of it and I've seen people implement this pattern in many different ways.

Upvotes: 1

AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

In your controller you should use one dbContext. Because When you try to update your model in db, you may get error. Because of different dbContext.

Check HERE

Upvotes: 1

Related Questions