I have a project called Infrastructure, which contains an interface IRepository
public interface IRepository<T>
{
/// <summary>
/// Adds the specified entity to the respository of type T.
/// </summary>
/// <param name="entity">The entity to add.</param>
void Add(T entity);
/// <summary>
/// Deletes the specified entity to the respository of type T.
/// </summary>
/// <param name="entity">The entity to delete.</param>
void Delete(T entity);
}
In my solution, i have two other projects
- Application.Web
- Application.Web.Api
- Infrastructure
Both projects, contains an implementation of the IRepository interface
public class EFRepository<T> : IRepository<T>
{
// DbContext for Application.Web project
ApplicationWebDbContext _db;
public EFRepository(ApplicationWebDbContext context)
{
_db = context;
}
public void Add(T entity) { }
public void Delete(T entity) { }
}
public class EFRepository<T> : IRepository<T>
{
// DbContext for Application.Web.Api project
ApplicationWebAPIDbContext _db;
public EFRepository(ApplicationWebAPIDbContext context)
{
_db = context;
}
public void Add(T entity) { }
public void Delete(T entity) { }
}
Both implementations works with different DataContexts.
How can I bind this in ninject?
private static void RegisterServices(IKernel kernel)
{
// bind IRepository for `Application.Web` project
kernel.Bind(typeof(IRepository<>)).To(typeof(Application.Web.EFRepository<>));
// bind IRepository for `Application.Web.Api' project
kernel.Bind(typeof(IRepository<>)).To(typeof(Application.Web.Api.EFRepository<>));
}
There are several appoaches to resolve such situations
Named binding
Simplest, just provide name for dependency:
And resolve it using this name. Name cound be found in configuration:
web.configfor example:Contextual binding
Find from injection context what type to bind. In your example based on target namespace
Get dependency from kernel: