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:
Cons:
IDataRepositoryFactory
interface as a dependency, feels a lot like using a service locator:
Is there not a better way?
Generic Factory interfaces aren't currently supported. So, that's already the best you can do.