Setting up a convention for automatic factories

半腔热情 提交于 2019-12-11 19:42:09

问题


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:

Pros:

  • No need to manually implement abstract factories anymore.

Cons:

  • 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.

Is there not a better way?


回答1:


Generic Factory interfaces aren't currently supported. So, that's already the best you can do.



来源:https://stackoverflow.com/questions/17729630/setting-up-a-convention-for-automatic-factories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!