私はNinjec、Ninject.Web.MVC、およびNinject.Web.Commonを使用しています
MVC アプリケーションを起動すると、次のバインド エラーが発生します。
バインディングで何が間違っていますか?
DbConnection のアクティブ化中にエラーが発生しました
一致するバインディングは利用できず、タイプは自己バインディング可能ではありません。
アクティベーション パス:
4) DbContext 型のコンストラクターのパラメーター existingConnection への依存関係 DbConnection の注入
3) GenericRepository{User} 型のコンストラクターのパラメーター dbContext への依存関係 DbContext の注入
2) 依存関係 IGenericRepository{User} を HomeController 型のコンストラクターのパラメーター リポジトリに挿入する
1) HomeController のリクエスト
提案:
1) DbConnection のバインディングを定義したことを確認します。
2) バインディングがモジュールで定義されている場合は、モジュールがカーネルにロードされていることを確認します。
3) 誤って複数のカーネルを作成していないことを確認してください。
4) コンストラクター引数を使用している場合は、パラメーター名がコンストラクターのパラメーター名と一致していることを確認してください。
5) モジュールの自動ロードを使用している場合は、検索パスとフィルターが正しいことを確認してください。
public interface IGenericRepository<T> where T : class
{
}
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
public GenericRepository(TLPContext dbContext)
{
DbContext = dbContext;
}
protected TLPContext DbContext { get; private set; }
}
[assembly: WebActivator.PreApplicationStartMethod(typeof(TLP.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(TLP.App_Start.NinjectWebCommon), "Stop")]
namespace TLP.App_Start
{
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using System;
using System.Web;
using TLP.DataAccess;
using TLP.DataAccess.Contract;
using TLP.DataAccess.Implementation;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
kernel.Bind<TLPContext>();
kernel.Bind(typeof(IGenericRepository<>)).To(typeof(GenericRepository<>));
return kernel;
}
}
}
[DbModelBuilderVersion(DbModelBuilderVersion.V5_0)]
public class TLPContext : DbContext
{
public TLPContext()
: base("DefaultConnection")
{
// We do not want implicit uncontrollable lazy loading, instead we use the explicit Load method
this.Configuration.LazyLoadingEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// Primary key
modelBuilder.Entity<User>().HasKey(p => p.UserId);
modelBuilder.Entity<User>().Property(p => p.FirstName).HasMaxLength(30).IsRequired();
modelBuilder.Entity<User>().Property(p => p.RegisteredAt).IsRequired();
}
public DbSet<User> Users { get; set; }
}