Unable to resolve service for type while attempting to activate

一曲冷凌霜 提交于 2020-12-19 07:10:26

问题


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

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

public class HomeController : Controller
    {
        private IRepository repository;

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

        public IActionResult Index()
        {
            return View(repository.Cities);
        }

    }

However I get this error:

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


回答1:


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

services.AddScoped<IRepository, MemoryRepository>();

AddScoped is just one example of a service lifetime. Note that:

Scoped lifetime services are created once per request.

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




回答2:


We are getting this error in Entity frame work core database first approach. I followed below steps and error got resolvedenter code here

Step 1: Check Your context class constructor should be like this

public partial class ZPHSContext : DbContext
{
    public ZPHSContext(DbContextOptions<ZPHSContext> dbContextOptions):base(dbContextOptions)
    {
    }
}

Step 2: In Startup file

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddDbContext<ZPHSContext>(options => options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}

Step 3: Connection string in appsettings

"ConnectionStrings": {
    "BloggingDatabase": "Server=Server=****;Database=ZPHSS;Trusted_Connection=True;"
}

Step 4: Remove default code in OnConfiguring method in context class

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}



回答3:


Other answers are CORRECT, however I was spinning up a new asp.net core 2.1.x project and got this error.

Ended up being a typo by ME.

So in my Controller instead of Correctly using the Interface like this

public HomeController(IApplicationRepository applicationRepository)
{
    _applicationRepository = applicationRepository;
}

My typo had me using ApplicationRepository instead of ApplicationRepository Notice below, and so with NO ERRORS spotting the missing "I" was fun :/

public HomeController(ApplicationRepository applicationRepository)
{
    _applicationRepository = applicationRepository;
}

Thus the controller was not resolving the DI...




回答4:


You have to add your implementation to DI (Dependeny Injection) section. For .Net Core Mvc, it would be like this:

 public void ConfigureServices(IServiceCollection services)
 {
   services.AddDbContext<ApplicationDbContext>(options =>
    options.UseInMemoryDatabase()
   );
   services.AddScoped<IRepository, MemoRepostory>();

 }



回答5:


This may not be helpful for your code sample but in my case the same error was a result of a circular dependency.




回答6:


A method like this needs to be added to your Startup:

    // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    //...

    // Add application services.
    services.AddTransient<IRepository, MemoryRepository>();

    //..
}

Services should be registered before used.

UPDATE: If you do not want to use DI on your application, just create and instance of MemoryRepository on the constructor of HomeController, like this:

public class HomeController : Controller
    {
        private IRepository repository;

        public HomeController()
        {
            repository = new MemoryRepository();
        }

        public IActionResult Index()
        {
            return View(repository.Cities);
        }

    }



回答7:


you have to register your repository like this

services.AddSingleton<IRepository, MemoryRepository>();



来源:https://stackoverflow.com/questions/46930090/unable-to-resolve-service-for-type-while-attempting-to-activate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!