Search code examples
c#entity-framework-6autofac

Dependency Injection in Unit of work with Autofac


Im going through a tutorial which uses EF 6 and a UnitOfWork pattern. The idea is to introduce Autofac and im not entirely sure how i should convert this line of code so it fits in with the project to introduce Dependency Injection

private readonly ContactsContext _context;

public UnitOfWork(ContactsContext context)
{
    _context = context;
    Customers = new CustomerRepository(_context);
}
   
public ICustomerRepository Customers { get; }

I can't change

Customers = new CustomerRepository(_context);

to

Customers = new ICustomerRepository(_context);

Note the Interface as it throws an error.

I can post the ICustomerRepository if required but I don't know how I should be handling the dependency in this case?

I can post more code if required but I didn't know if this is enough and I'm missing something simple or not?


Solution

  • The standard way to do this would be to take a constructor dependency on ICustomerRepository instead of instantiating a CustomerRepository yourself within the constructor:

    private readonly ContactsContext _context;
    public UnitOfWork(ContactsContext context, ICustomerRepository customerRepository)
    {
         _context = context;
         Customers = customerRepository;
    }
       
    public ICustomerRepository Customers { get; }
    

    Of course, you will also need to register CustomerRepository with Autofac as the implementation of ICustomerRepository.

    builder.RegisterType<CustomerRepository>().As<ICustomerRepository>();
    

    This means that you will be relying on Autofac to create the repository instead of doing so yourself (Autofac will 'know' to inject the ContactsContext into the constructor of CustomerRepository). That's the pervasive aspect of dependency injection - it ends up requiring you to adopt it all the way down.