0

通过使用泛型方法定义IDataRepositoryFactory非泛型接口:Create

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接口作为依赖项,感觉很像使用服务定位器
    • 全能的通用工厂可以创建任何存储库类型,甚至是完全不相关模块的命名空间中的存储库类型。
    • 实际的依赖关系现在隐藏在抽象工厂后面;消费者的构造函数不再静态记录所需的存储库/工厂。

没有更好的方法吗?

4

1 回答 1

0

当前不支持通用工厂接口。所以,这已经是你能做的最好的了。

于 2013-07-19T10:31:30.897 回答