问题
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