【发布时间】:2013-07-18 16:56:08
【问题描述】:
通过使用通用Create 方法定义IDataRepositoryFactory 非通用接口:
public interface IDataRepositoryFactory
{
T Create<T>(DataContext context) where T : IDataRepository; // new non-generic interface
}
我能够避免编写工厂实现:
_kernel.Bind(t => t.FromAssemblyContaining(typeof(DataRepository<>))
.SelectAllInterfaces()
.EndingWith("RepositoryFactory")
.BindToFactory());
_kernel.Bind(t => t.FromAssemblyContaining(typeof(DataRepository<>))
.SelectAllClasses()
.WhichAreNotGeneric()
.EndingWith("Repository")
.BindAllInterfaces());
但是这个解决方案有利有弊:
优点:
- 不再需要手动实现抽象工厂。
缺点:
- 将此
IDataRepositoryFactory接口作为依赖项,感觉很像使用服务定位器:- 全能的泛型工厂可以创建任何存储库类型,甚至是完全不相关模块的命名空间中的存储库类型。
- 实际依赖关系现在隐藏在抽象工厂后面;消费者的构造函数不再静态记录所需的存储库/工厂。
没有更好的办法吗?
【问题讨论】:
标签: c# ninject factory convention-over-configur