【问题标题】:Error activating Interface激活接口时出错
【发布时间】:2017-08-09 18:20:10
【问题描述】:

我是 .NET 的新手。我正在创建一个网上商店,但我遇到了问题

我的错误:

错误激活 IBookRepository 没有匹配的绑定 可用,且类型不可自绑定。激活路径:2) 将依赖项 IBookRepository 注入到参数 repo 中 BooksController 类型的构造函数 1) BooksController 的请求

建议:1) 确保您已为 IBook 存储库。 2) 如果绑定是在模块中定义的,请确保 该模块已加载到内核中。 3) 确保你有 不会意外创建多个内核。 4)如果您正在使用 构造函数参数,确保参数名称与 构造函数参数名称。 5)如果您使用的是自动模块 加载中,确保搜索路径和过滤器正确。

我在解决方案中使用 3 个项目我在 c# 类库域中有一个接口 IBookRepository 并在控制器中使用 asp.net mvc

IBookRepository:

using Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain.Abstract
{
    public interface IBookRepository
    {
        IEnumerable<Book> Books { get; }
    }
}

书籍控制器:

using Domain.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebUI.Controllers
{
    public class BooksController : Controller
    {
        private IBookRepository repository;
        public BooksController(IBookRepository repo)
        {
            repository = repo;
        }

        public ViewResult List()
        {
            return View(repository.Books);
        }
    }
}

我对所有构造函数参数类型都有一个绑定:

 private static void RegisterServices(IKernel kernel)
    {
        System.Web.Mvc.DependencyResolver.SetResolver(new WebUI.Infrastructure.NinjectDependencyResolver(kernel));
    }

我该如何解决这个问题?

【问题讨论】:

  • 您仍然需要在 Ninject 绑定文件中定义映射。

标签: c# .net asp.net-mvc visual-studio


【解决方案1】:

所以你已经完成了依赖注入的第一步,但是你需要告诉你的代码当你的接口被请求时使用什么具体类。为此,您需要为您的具体类创建一个绑定。

为此,您需要导航到您的 Ninject 绑定文件并添加以下内容:

Bind<IBookRepository>().To<NameOfYourClassThatImplementsIBookRepository>();

显然NameOfYourClassThatImplementsIBookRepository 应该替换为您的具体类的实际名称(即实现您的接口的类)。

【讨论】:

  • 非常感谢您帮助我)
【解决方案2】:

我不知道 Ninject,但是看上面的代码,BookController 构造函数需要一个实现 IBookRepository 的类的实例。考虑构造函数链或多一个默认构造函数来将实例传递给上面编写的构造函数。

using Domain.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebUI.Controllers
{
    public class BooksController : Controller
    {
        private IBookRepository repository;

public BooksController():this(new BookRepository())
        {

        }
        public BooksController(IBookRepository repo)
        {
            repository = repo;
        }

        public ViewResult List()
        {
            return View(repository.Books);
        }
    }
}

【讨论】:

  • 什么是 BookRepository ?
  • 实现 IBookRepository 的具体类
  • OP 显然在使用依赖注入,您的回答完全消除了这一点。
猜你喜欢
  • 2014-03-06
  • 1970-01-01
  • 2017-01-01
  • 1970-01-01
  • 2019-03-13
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多