6

Infrastructureインターフェイスを含むというプロジェクトがあります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);
}

私のソリューションでは、他に2つのプロジェクトがあります

  • アプリケーション.Web
  • Application.Web.Api
  • インフラストラクチャー

IRepository両方のプロジェクトには、インターフェースの実装が含まれています

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でバインドするにはどうすればよいですか?

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<>));    
}
4

1 に答える 1

23

このような状況を解決するためのいくつかのアプローチがあります

名前付きバインディング

最も簡単なのは、依存関係の名前を指定するだけです:

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

そして、この名前を使用して解決します。名前は設定で見つけることができます:web.config例:

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

コンテキスト バインディング

インジェクション コンテキストから、バインドするタイプを見つけます。ターゲット名前空間に基づくあなたの例では

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>();
于 2013-01-14T09:20:57.887 に答える