如何注入一个工厂的泛型类型与Autofac的 [英] How to inject a factory of generic types with Autofac
问题描述
我有一个仓库工厂 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容器。所以,我应该以某种方式注入 Func键< IRepository< 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.
推荐答案
的 NhRepositoryFactory
不包含业务逻辑,可以是你的根组成的一部分。这使您可以让它具有对容器的引用。 这仅仅是力学并不认为是服务定位器反模式。在 NhRepositoryFactory
将是这样的:
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();
这篇关于如何注入一个工厂的泛型类型与Autofac的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!