Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

c# - Unable to resolve service for type while attempting to activate

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

InvalidOperationException: Unable to resolve service for type 'Cities.Models.IRepository' while attempting to activate 'Cities.Controllers.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);
}

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

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)
    {
        ...
    }
}
question from:https://stackoverflow.com/questions/46930090/unable-to-resolve-service-for-type-while-attempting-to-activate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For the Dependency Injection framework to resolve IRepository, it must first be registered with the container. For example, in ConfigureServices, add the following:

services.AddScoped<IRepository, MemoryRepository>();

AddScoped is just one example of a service lifetime:

For web applications, a scoped lifetime indicates that services are created once per client request (connection).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...