Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16320

Correct usage of Repository Factory pattern?

My repository pattern is setup like this:

public interface IRepository<T> where T : class {}

public abstract class Repository<C, T> : IRepository<T> 
    where C : DbContext, IBaseContext 
    where T : class, IEntity 
{}

public interface ICustomerRepository : IRepository<Customer> 
{//specific methods here}

public class CustomerRepository : Repository<MyContext, Customer>, ICustomerRepository

I added the following method in my UoW class (and interface):

public TRepository GetRepository<TEntity, TRepository>() 
    where TEntity : class, IEntity 
    where TRepository : IRepository<TEntity>
{
    object[] args = new object[] { (IDatabaseFactory<MyContext>)databaseFactory };
    return (TRepository)Activator.CreateInstance(typeof(TRepository), args);
}

And in my service I try to get the repository doing the following:

var customerRepository = uow.GetRepository<Customer, CustomerRepository>();

In Autofac i'm using InstancePerRequest. So the UoW and the repository instances are created per request and disposed afterwards. Do I still need to implement caching of the repositories?

Is this the correct way to use repository factory?

NOTE

My UoW and repositories are located in a 'DAL' assembly, my services are in a different 'Service' assembly.

Upvotes: 1

Views: 9113

Answers (1)

Steve Lillis
Steve Lillis

Reputation: 3256

A factory's only job is to construct instances of classes. So in that sense, your factory is correct.

Your IoC container is already managing the life time of the object so there is no need to duplicate that work.

My question is this: Why even have a factory? Your IoC container is already capable of constructing instances. Why not just request an ICustomerRepository from Autofac directly and have it construct for you, instead of requesting a custom object who's only job is to do what Autofac can do out of the box?

Upvotes: 2

Related Questions