我在ASP.NET MVC项目中从Ninject 3.0.1.10获得臭名昭着的“错误激活XYZ。没有匹配的绑定可用blah blah blah”。
以下是我如何设置我的绑定(非常简单):
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
string connectionString = WebConfigurationManager.ConnectionStrings["STAGING"].ConnectionString;
kernel.Bind<IUserAccountRepository>()
.To<SqlUserAccountRepository>()
.WithConstructorArgument("connectionString", connectionString);
kernel.Bind<IRecipeRepository>()
.To<SqlRecipeRepository>()
.WithConstructorArgument("connectionString", connectionString);
kernel.Bind<HomeViewModel>().ToSelf();
}
}
当调用控制器索引操作时,它会尝试创建一个HomeViewModel对象:
public ActionResult Index()
{
IKernel kernel = new StandardKernel();
HomeViewModel model = kernel.Get<HomeViewModel>();
...
触发异常:
Error activating IRecipeRepository No matching bindings are available, and the type is not self-bindable.
Activation path:
2) Injection of dependency IRecipeRepository into parameter recipeRepository of constructor of type HomeViewModel
1) Request for HomeViewModel
但是如果我在RegisterServices中调用kernel.Bind之后直接尝试获取HomeViewModel的实例,那么它可以正常工作。
以下是HomeViewModel的样子(为简洁起见,删除了一些细节):
public class HomeViewModel
{
public HomeViewModel(IRecipeRepository recipeRepository,
IUserAccountRepository userAccountRepository)
{
this.recipeRepository = recipeRepository;
this.userAccountRepository = userAccountRepository;
}
//
// Some details removed for sake of brevity
//
private readonly IRecipeRepository recipeRepository;
private readonly IUserAccountRepository userAccountRepository;
}
知道我错过了什么吗?为什么控制器在这种情况下“特殊”?