-->

设置为自动工厂公约(Setting up a convention for automatic fa

2019-11-02 06:57发布

通过定义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接口作为依赖,感觉就像使用服务定位器有很多:
    • 全能的通用工厂可以创建任何存储库类型,即使是那些在完全不相关的模块命名空间。
    • 实际的依赖现在的背后隐藏着一个抽象工厂; 消费者的构造不再静态文档所需的仓库/工厂。

有没有更好的办法?

Answer 1:

目前不支持通用工厂接口。 所以,这是已经可以做到最好。



文章来源: Setting up a convention for automatic factories