Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 readonly 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 readonly List<City> cities = new List<City>();      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)     {         ...     } } 
like image 710
Vojislav Kovacevic Avatar asked Oct 25 '17 10:10

Vojislav Kovacevic


People also ask

What is difference between AddTransient and AddScoped?

AddTransient() - This method creates a Transient service. A new instance of a Transient service is created each time it is requested. AddScoped() - This method creates a Scoped service. A new instance of a Scoped service is created once per request within the scope.

What is IServiceCollection in .NET core?

AddScoped(IServiceCollection, Type, Type) Adds a scoped service of the type specified in serviceType with an implementation of the type specified in implementationType to the specified IServiceCollection.

Which exception may be caused by missing service registrations?

Open generic types aren't checked The service provider validation completely skips over the open generic registration, so it never detects the missing DataService dependency. The app starts up without errors, and will throw a runtime exception if you try to request a ForecastService<T> .

What is dependency injection C# with example?

Using dependency injection, we can pass an instance of class C to class B, and pass an instance of B to class A, instead of having these classes to construct the instances of B and C. In the example, below, class Runner has a dependency on the class Logger.


2 Answers

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

For .NET 6+, which uses the new hosting model by default, add the following in Program.cs instead:

builder.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.

like image 90
Kirk Larkin Avatar answered Sep 19 '22 02:09

Kirk Larkin


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=****;Database=ZPHSS;Trusted_Connection=True;" } 

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

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { } 
like image 25
karunakar bhogyari Avatar answered Sep 19 '22 02:09

karunakar bhogyari