我有一个名为 Infrastructure
的项目,其中包含一个接口(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);
}
在我的解决方案中,我还有另外两个项目
- Application.Web
- Application.Web.Api
- 基础设施
两个项目,都包含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) { }
}
两种实现都适用于不同的DataContexts
。
如何在 ninject 中绑定(bind)它?
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<>));
}
最佳答案
有several appoaches解决这种情况
命名绑定(bind)
最简单,只需提供依赖项的名称:
kernel
.Bind(typeof(IRepository<>))
.To(typeof(WebApiEFRepository<>))
// named binding
.Named("WebApiEFRepository");
并使用这个名称解析它。名称可以在配置中找到:web.config
例如:
var webApiEFRepository = kernel.Get<IRepository<Entity>>("WebApiEFRepository");
上下文绑定(bind)
从 injection context 中查找要绑定(bind)什么类型。 在您基于目标 namespace 的示例中
kernel
.Bind(typeof(IRepository<>))
.To(typeof(WebDbRepository<>))
// using thins binding when injected into special namespace
.When(request => request.Target.Type.Namespace.StartsWith("Application.Web"));
从内核获取依赖:
// WebDbRepository<> will be injected
var serice = kernel.Get<Application.Web.Service>();
关于c# - Ninject:将相同的接口(interface)绑定(bind)到两个实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14315312/