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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With