尝试激活时无法解析服务类型 [英] Unable to resolve service for type while attempting to activate

查看:47
本文介绍了尝试激活时无法解析服务类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET Core应用程序中,出现以下错误:

In my ASP.NET Core application, I get the following error:

InvalidOperationException:尝试激活"Cities.Controllers.HomeController"时,无法解析类型为"Cities.Models.IRepository"的服务.

InvalidOperationException: Unable to resolve service for type 'Cities.Models.IRepository' while attempting to activate 'Cities.Controllers.HomeController'.

我正在尝试将 Cities getter传递给视图,例如 HomeController :

I the HomeController I am trying to pass the Cities getter to the view like so:

public class HomeController : Controller
{
    private IRepository repository;

    public HomeController(IRepository repo)
    {
        repository = repo;
    }

    public IActionResult Index() => View(repository.Cities);
}

我有一个文件 Repository.cs ,其中包含一个接口及其实现,如下所示:

I have one file Repository.cs that contains an interface and its implementation like so:

public interface IRepository
{
    IEnumerable<City> Cities { get; }
    void AddCity(City newCity);
}

public class MemoryRepository : IRepository
{
    private List<City> cities = new List<City> {
        new City { Name = "London", Country = "UK", Population = 8539000},
        new City { Name = "New York", Country = "USA", Population = 8406000 },
        new City { Name = "San Jose", Country = "USA", Population = 998537 },
        new City { Name = "Paris", Country = "France", Population = 2244000 }
    };

    public IEnumerable<City> Cities => cities;

    public void AddCity(City newCity) => cities.Add(newCity);
}

我的 Startup 类包含从模板中默认生成的代码.我进行了任何更改:

My Startup class contains the default-generated code from the template. I have made any changes:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ...
    }
}

推荐答案

您需要向Dependency Injection框架注册 IRepository .例如,在 ConfigureServices 中,添加以下内容:

You need to register IRepository with the Dependency Injection framework. For example, in ConfigureServices, add the following:

services.AddScoped<IRepository, MemoryRepository>();

AddScoped 只是服务寿命.请注意:

范围内的生命周期服务每个请求创建一次.

Scoped lifetime services are created once per request.

有关依赖关系的更多信息,请参见文档在ASP.NET Core中进行注入.

See the docs for more information on Dependency Injection in ASP.NET Core.

这篇关于尝试激活时无法解析服务类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆