gpt4 book ai didi

dependency-injection - 具有开放通用接口(interface)的温莎类型工厂

转载 作者:行者123 更新时间:2023-12-04 08:21:10 24 4
gpt4 key购买 nike

在我的应用程序中,我想依赖一个类中的多个存储库,而并非每次都需要所有这些存储库。我没有在不必要的地方构造每个实例,而是使用 Typed Factory facility在温莎。

但是,为每个存储库注册一个工厂有点烦人,我想用一个开放的通用注册来代替它。我想要做的是类似下面的事情:

container.Register(
Component.For<IFactory<IRepository<>>>().AsFactory()
);

但是,这是一个语法错误,因为缺少 IRepository 的类型参数。是否有我可以使用的语法来完成这项工作?

注意:我知道我可以注册一个非类型化工厂接口(interface)并使用它来创建多个组件。我对这样做不感兴趣,因为这本质上依赖于服务定位器——如果我没有注册依赖项,那么在代码尝试使用它之前我不会知道它——我知道我的方法this 在构造函数中,即使我还没有创建实例。

完整(简化)示例如下:

public class TestA { }
public class TestB { }
public interface IRepository<T> { T Create(); }
public class Repository<T> : IRepository<T>
{
public T Create() { return Activator.CreateInstance<T>(); }
}

public interface IFactory<T>
{
T Create();
void Release(T instance);
}

class Program
{
static void Main(string[] args)
{
IWindsorContainer container = new WindsorContainer();
container.AddFacility<TypedFactoryFacility>();

container.Register(
// Individual registrations of repositories here are fine
Component.For<IRepository<TestA>>().ImplementedBy<Repository<TestA>>(),
Component.For<IRepository<TestB>>().ImplementedBy<Repository<TestB>>()
);

container.Register(
// Individual registrations of factories - works, but trying to avoid!
Component.For<IFactory<IRepository<TestA>>>().AsFactory(),
Component.For<IFactory<IRepository<TestB>>>().AsFactory()
);

container.Register(
// Generic Registration of Factories - syntax errors
// Component.For<IFactory<IRepository<>>>().AsFactory()
// Component.For(typeof(IFactory<IRepository<>>)).AsFactory()
);

var factoryA = container.Resolve<IFactory<IRepository<TestA>>>();
var factoryB = container.Resolve<IFactory<IRepository<TestB>>>();

var repoA = factoryA.Create();
var repoB = factoryB.Create();

Console.WriteLine("Everything worked");
}
}

最佳答案

你的工厂接口(interface)定义有点太“开放”了。按如下方式更改您的工厂界面:

public interface IRepositoryFactory<T>
{
IRepository<T> Create();
void Release(IRepository<T> instance);
}

然后您可以注册:

container.Register(Component.For(typeof(IRepositoryFactory<>)).AsFactory());

并解决:

var factoryA = container.Resolve<IRepositoryFactory<TestA>>();
var factoryB = container.Resolve<IRepositoryFactory<TestB>>();

关于dependency-injection - 具有开放通用接口(interface)的温莎类型工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12881772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com