建立自动工厂的约定 [英] Setting up a convention for automatic factories
本文介绍了建立自动工厂的约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通过使用通用Create
方法定义IDataRepositoryFactory
非通用接口:
By defining a IDataRepositoryFactory
non-generic interface with a generic Create
method:
public interface IDataRepositoryFactory
{
T Create<T>(DataContext context) where T : IDataRepository; // new non-generic interface
}
我能够避免编写工厂实现:
I'm able to avoid having to write factory implementations:
_kernel.Bind(t => t.FromAssemblyContaining(typeof(DataRepository<>))
.SelectAllInterfaces()
.EndingWith("RepositoryFactory")
.BindToFactory());
_kernel.Bind(t => t.FromAssemblyContaining(typeof(DataRepository<>))
.SelectAllClasses()
.WhichAreNotGeneric()
.EndingWith("Repository")
.BindAllInterfaces());
但是此解决方案有其优点和缺点:
However this solution has pros and cons:
优点:
- 不再需要手动实现抽象工厂.
缺点:
- 将此
IDataRepositoryFactory
接口作为依赖项,感觉很像使用服务定位器:- 功能强大的通用工厂可以创建任何存储库类型,甚至可以在完全不相关的模块的命名空间中创建存储库类型.
- 实际依赖项现在隐藏在抽象工厂的后面;消费者的构造函数不再静态地记录所需的存储库/工厂.
- Having this
IDataRepositoryFactory
interface as a dependency, feels a lot like using a service locator:- The all-powerful generic factory can create any repository type, even those in namespaces of completely unrelated modules.
- Actual dependencies are now hidden behind an abstract factory; the consumer's constructor no longer statically documents the required repositories/factories.
有没有更好的方法?
推荐答案
当前不支持通用工厂接口.因此,这已经是您所能做的最好的事情.
Generic Factory interfaces aren't currently supported. So, that's already the best you can do.
这篇关于建立自动工厂的约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文