【问题标题】:Ninject - Error loading Ninject component ICacheNinject - 加载 Ninject 组件 ICache 时出错
【发布时间】:2015-09-03 13:49:55
【问题描述】:

我是依赖注入的新手,目前使用 Ninject 作为我的 DI。我一直在玩 ASP.Net MVC 5 应用程序并且一直在阅读“Pro ASP.NET MVC 5”。我已经按照书中有关如何设置和使用 Ninject 的示例进行操作。以下是我的注册服务的代码:

    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<ICustomerRepository>().To<CustomerRepository>();
        kernel.Bind<ICustomerUserDataRepository>().To<CustomerUserDataRepository>();
    } 

至于我的控制器,我有以下:

public class CustomerController : Controller
{
    private ICustomerRepository customerRepository;

    public CustomerController(ICustomerRepository customerRepo)
    {
        this.customerRepository = customerRepo;
    }

    // GET: Customer
    public ActionResult Index(int Id = 0)
    {
        Customer customer = customerRepository.GetCustomer(Id).First();

        return View(customer);
    }
}

这正如书中预期的那样工作得很好。但是,我一直在玩一些其他代码,并想进一步使用 Ninject 来解决一些依赖关系。例如,我正在为我的 Razor 视图之一开发自定义助手。在我的帮助代码中,我有以下内容:

       using (IKernel kernel = new StandardKernel())
       {                
            ICustomerUserDataRepository customerUserDataRepo = kernel.Get<ICustomerUserDataRepository>();

当我运行它时,它抱怨没有为 ICustomerUserDataRepository 定义绑定。我假设这是因为我使用的是没有定义绑定的新内核。我读到您需要通过模块在内核中加载绑定。所以我做了以下:

public class MyBindings : NinjectModule
{
    public override void Load()
    {
        Bind<ICustomerUserDataRepository>().To<CustomerUserDataRepository>();
    }
}

然后我在下面设置我的内核时加载模块:

using (IKernel kernel = new StandardKernel(new MyBindings()))
{                
       ICustomerUserDataRepository customerUserDataRepo = kernel.Get<ICustomerUserDataRepository>();

但是,当我执行应用程序时,这会导致“加载 Ninject 组件 ICache 时出错”错误消息。对于我做错了什么和我不理解的事情,我将不胜感激。我读到多个定义的内核可能会导致此错误。我是否不应该在我的辅助方法中使用新内核,因为已经在 RegisterServices() 下使用和绑定了一个新内核?如果是这样,我是否想在我的辅助方法中访问该现有内核?或者我是否走在正确的轨道上并且需要一个新的内核来加载我的模块中的特定绑定?谢谢。

【问题讨论】:

    标签: asp.net-mvc dependency-injection ninject


    【解决方案1】:

    我不应该在我的辅助方法中使用新内核,因为已经在 RegisterServices() 下使用和绑定了一个新内核?

    正确。每个应用程序只需要一个内核或组合根。我建议不要尝试在辅助方法中访问依赖项,而是在控制器中创建一个视图模型(可以访问依赖项),然后将视图模型传递给辅助方法。

    【讨论】:

    • 感谢您的回复,并会试一试!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    相关资源
    最近更新 更多