Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top