I am creating a base repository class with the Entity Framework where it inherits the entire Entities repository. I want to inject a DatabaseContext
into a base class using Injection Dependency using Ninject. I think the Injection constructor is the right way, but when executing the Constructor Injection in a derived class, I have to pass the parameter to the constructor in the base class, and I don't want that. So is a setter injection more appropriate?
Here is my code:
public abstract class BaseRepository<TEntity> : IDisposable where TEntity : class { private readonly DatabaseContext _databaseContext; protected BaseRepository(DatabaseContext databaseContext) { this._databaseContext = databaseContext; } }
Using the Injection constructor in the above example, in my derived class I have to pass the BaseContext object to the base class, I do not like to do this with the whole derived class :
public class UsuarioRepository : BaseRepository<IUsuario>, IUsuarioRepository { public UsuarioRepository(DatabaseContext databaseContext) : base(databaseContext) { } }
Embedding a Setter instead of a Constructor Injection is a good way to solve this? What is the best way?
Update:
Using Setter Injection, my derived class will not have constructors:
public class UsuarioRepository : BaseRepository<IUsuario>, IUsuarioRepository { }
My context is just one application. I don’t need a derived class to pass a context object, but I like to introduce it into the base class to use mocks for tests in the future.
Solve the problem of:
Sorry, I'm confusing the question, but I solve my problem by creating 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 this:
public class UsuarioRepository : BaseRepository<IUsuario>, IUsuarioRepository { }
And My Factory like this:
public class ContextFactory { public DatabaseContext GetCurrentContext() { return new DatabaseContext(); } }