Dmitriy Melnik
Dmitriy Melnik

Reputation: 530

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.

Upvotes: 6

Views: 10432

Answers (2)

Steven
Steven

Reputation: 172606

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();

Upvotes: 9

Danielg
Danielg

Reputation: 2699

Autofac is also able to handle the generic creation natively without the factory.

builder.RegisterGeneric(typeof(NhRepository<>))
    .As(typeof(IRepository<>))
    .InstancePerLifetimeScope();

Using this pattern you can simply take a dependency on IRepository and autofac will fill out the dependencies.

Upvotes: 5

Related Questions