Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a factory of generic types with Autofac

I have a repository factory NhRepositoryFactory

public interface IRepositoryFactory  
{  
  IRepository<T> Create<T>() where T: Entity;  
} 

public class NhRepositoryFactory: IRepositoryFactory  
{  
  public IRepository<T> Create<T>() where T : Entity  
  {  
    return new NhRepository<T>();  
  }  
}

In order to resolve some repositories dependencies I want to get them from the Autofac container. So I should somehow inject Func<IRepository<T>> factory into my class. How can I accomplish this?
Thanks in advance.

like image 296
Dmitriy Melnik Avatar asked Mar 12 '12 08:03

Dmitriy Melnik


1 Answers

The NhRepositoryFactory contains no business logic and can be part of your composition root. This allows you to let it have a reference to the container. This is just mechanics and is not considered to be the Service Locator anti-pattern. The NhRepositoryFactory will look like this:

// This class is part of your composition root
public class NhRepositoryFactory : IRepositoryFactory  
{
    private readonly Container container;

    public NhRepositoryFactory(Container container)
    {
        this.container = container;
    }

    public IRepository<T> Create<T>() where T : Entity  
    {  
        return this.container.Resolve<NhRepository<T>>();
    }  
}

And you can register it like this:

builder.Register<IService>(c => new NhRepositoryFactory(c))
    .SingleInstance();
like image 180
Steven Avatar answered Sep 29 '22 08:09

Steven