i'm building a repository base class with Entity Framework where all Entities repository will inherit. I want to inject the DatabaseContext
in base class using Dependency Injection using Ninject. I think the Constructor Injection is the right way, but doing this with Constructor Injection in derived class I will must to pass parameter to constructor in base class and I don't want it. Therefore, a Setter Injection is more appropriate?
Here's my code:
public abstract class BaseRepository<TEntity> : IDisposable
where TEntity : class
{
private readonly DatabaseContext _databaseContext;
protected BaseRepository(DatabaseContext databaseContext)
{
this._databaseContext = databaseContext;
}
}
Using Constructor Injection in the above example, in my derived class I will must to pass databaseContext object to base class, I don't like to doing this to all my derived class:
public class UsuarioRepository : BaseRepository<IUsuario>,
IUsuarioRepository
{
public UsuarioRepository(DatabaseContext databaseContext)
: base(databaseContext)
{
}
}
Setter Injection instead of Constructor Injection is a good way to solve that? What is the best way?
Update:
Using Setter Injection my derived class's will not have constructors:
public class UsuarioRepository : BaseRepository<IUsuario>, IUsuarioRepository
{
}
My Context is only one in all application. I don't need derived class to pass context object, but i like to inject it in base class to using mocks for tests in future.
I Solve the problem:
Sorry, I'm confusing with the question, but i'm solving my problem building a Factory:
public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity>
where TEntity : class
{
private readonly ContextFactory _contextFactory = new ContextFactory();
protected DatabaseContext CurrentContext
{
get
{
return this._contextFactory.GetCurrentContext();
}
}
}
And my derived class will look like that:
public class UsuarioRepository : BaseRepository<IUsuario>, IUsuarioRepository
{
}
And My Factory like that:
public class ContextFactory
{
public DatabaseContext GetCurrentContext()
{
return new DatabaseContext();
}
}
Best Answer
Property Injection implies that the dependency is optional, while Constructor Injection implies that the dependency is required. Choose a pattern accordingly.
In more than 95% of the cases Constructor Injection is the correct pattern. What about it don't you like?