I'm currently trying to implement the Repository Pattern on top of my DbContext. The thing is, I eventually end up with a situation where I have to inject several Repositories into a UnitOfWork constructor, like this:
public class UnitOfWork
{
private DbContext _context;
ICustomerRepository Customers { get; private set; }
IEmployeeRepository Employees { get; private set; }
public UnitOfWork(DbContext context, ICustomerRepository cust, IEmployeeRepository emp)
{
_context = context;
Customers = cust;
Employees = emp;
}
}
However, since all of them would have to share the same DbContext, I can't see injecting them as an option.
That's why I was thinking about creating a RepositoryFactory class, but since all of the repositories inherit from a generic interface I found it impossible to create a single Create() method, because, after all, they have no real common ancestor that would be a valid return type.
To give you some more insight, that's how the code looks like:
public interface IRepository<TEntity> where TEntity:class
{
TEntity Get(int id);
IEnumerable<TEntity> GetAll();
}
public interface ICustomerRepository : IRepository<Customer>
{
IEnumerable<Customer> GetSeniorCustomers();
}
public class CustomerRepository : ICustomerRepository
{
private readonly DbContext _context;
public CustomerRepository(DbContext context) : base(context)
{
_context = context;
}
// ... implementation of ICustomerRepo here
}
Now, that's the current state of things:
And what I'd like to be able to do is:
public UnitOfWork(DbContext context, RepositoryFactory fac)
{
_context = context;
Customers = fac.Create(context, RepoType.Customer);
Employees = fac.Create(context, RepoType.Employee);
}
I know it doesn't really give me any additional flexibility, but it does keep the code a bit less clunky in my opinion.
But, as I mentioned earlier, I cannot think of a valid return type for the Create() method.
So, I came up with the idea to create multiple methods inside the RepositoryFactory class, instead of a single parameterized one, like this:
public class RepositoryFactory
{
public ICustomerRepository CreateCustomerRepo(DbContext context){/*...*/}
public IEmployeeRepository CreateEmployeeRepo(DbContext context){/*...*/}
}
So the questions are:
- Can the thing I'm doing be even called a Factory Method?
- If not, is it at least a valid solution? If not, how can I achieve the same thing in a cleaner manner?
By achieve the same thing I mean implement a way of creating those repositories in a managable, concise way.
Thank you for all the help in advance.