2
votes

I've 10 POCO class. I'm using a simple repository pattern with unit of work with IRespoitory interface and UnitOf work class.

Is it right (normal) put all my IRepository in a single UnitOfWork instance?

Namely: 10 POCO class - 10 instance of IRepository - Only one UnitOfWork class which contains all 10 repository

UnitOfWork
{
IRepository<Customer> CustomerRepository {get; set;}
IRepository<Customer> CustomerRepository {get; set;}
IRepository<Customer> CustomerRepository {get; set;}
// the same for all others 7 POCo class
// ..other stff
}
2

2 Answers

0
votes

It's a little like the EF DataContext.

DataContext of EntityFramework is a unit of work and a little like a repository (or collection of your repositories).

I prefer to separate these things and use a dependency injection framework (like structuremap).

You can ask structuremap for IRepository<Customer> and it will give you the instance.

Separate UoW from your Repositories.

You can have one UoW class (with methods like: SubmitChanges) and then Your Repositories (each with methods like: Add, Delete, ...)

0
votes

Yes, your approach is right (normal) with one Unit Of Work class/instance contains all repositories (of POCO classes).

The UoW brings 2 important things/advantages for me;

  1. The obvious one is the ACID (Atomic, Consistency, Isolation, Durability) transactions, as only one dbcontext tracks and updates all db changes.

  2. Unit of Work reduce a lot of dependency Injection.

Here is a complete example of using UoW with repositories;

public interface IUnitOfWork
{
    IRepository<Customer> Customers { get; }
    IRepository<Order> Orders { get; }
    // the same for all others 8 POCO class

    Task<int> SaveAsync();
}

=============================================================

public class UnitOfWork : IUnitOfWork
{
    public IRepository<Customer> Customers { get; private set; }
    public IRepository<Order> Orders { get; private set; }
    // the same for all others 8 POCO class

    private readonly MyDBContext _Context;

    public UnitOfWork(MyDBContext context)
    {
        _dbContext       = context;
        Customers        = new Repository<Customer>(_dbContext);
        Orders           = new Repository<Order>(_dbContext);
        // the same for all others 8 POCO class
    }

    public async Task<int> SaveAsync()
    {
        return await _dbContext.SaveChangesAsync();
    }
}

AS you can see in the above implementation that one dbContext has been used to generate all repositories. This will bring the ACID functionality.

And in your Services/Controller (or anywhere you want to use your repositories), you just need to inject only 1 UoW and can access all your repositories as:

    _uow.Customers.Add(new Customer());
    _uow.Ordres.Update(order);
    _uow.SaveAsync();