0

我在一个 ASP.NET MVC 项目中从 Ninject 3.0.1.10 中得到臭名昭著的“激活 XYZ 时出错。没有匹配的绑定可用等等等等”。

以下是我设置绑定的方式(非常简单):

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

当调用控制器 Index 操作时,它会尝试创建一个 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;
}

知道我错过了什么吗?为什么在这种情况下控制器是“特殊的”?

4

0 回答 0