我有一个存储库工厂 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>();
}
}
为了解决一些存储库依赖关系,我想从 Autofac 容器中获取它们。所以我应该以某种方式注入(inject) Func<IRepository<T>>
工厂进我类。我怎样才能做到这一点?
提前致谢。
最佳答案
NhRepositoryFactory
不包含任何业务逻辑,可以作为组合根的一部分。这允许您让它拥有对容器的引用。 This is just mechanics并且不被视为服务定位器反模式。 NhRepositoryFactory
将如下所示:
// 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>>();
}
}
你可以这样注册:
builder.Register<IService>(c => new NhRepositoryFactory(c))
.SingleInstance();
关于c# - 如何使用 Autofac 注入(inject)泛型工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9663892/