c# - Ninject:将相同的接口(interface)绑定(bind)到两个实现

标签 c# asp.net-mvc ninject ninject.web.mvc

我有一个名为 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/

相关文章:

jquery - MVC 部分 View 中的命名约定以避免 ID 冲突

c# - 从元数据中提取错误验证消息

c# - 如何使用 ninject 在 HttpModule 中注入(inject)依赖项?

asp.net-mvc-3 - ASP.NET MVC3 Fluent Validation Constructor 每个请求命中多次

asp.net-mvc - 如何从编辑器模板添加 JavaScript 或 css 引用

c# - LINQ 中基于组的字段连接

c# - 循环到 LINQ 转换 -

c# - 避免输入参数出现 "null entry for parameter id of non-nullable type"错误的干净方法

c# - 在 NInject 中实现 OnePerSessionBehavior

c# - 静态类还是动态类?