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:

kernel
        .Bind(typeof(IRepository<>))
        .To(typeof(WebApiEFRepository<>))
        // named binding
        .Named("WebApiEFRepository");

And resolve it using this name. Name cound be found in configuration: web.config for example:

var webApiEFRepository = kernel.Get<IRepository<Entity>>("WebApiEFRepository");

Contextual binding

Find from injection context what type to bind. In your example based on target 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"));

Get dependency from kernel:

// WebDbRepository<> will be injected
var serice = kernel.Get<Application.Web.Service>();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top