Article

Unable to resolve service for type while attempting to activate

In this article we will see why this error show Unable to resolve service for type while attempting to activate.

At this point, if we run the project we get the following error Unable to resolve service for type while attempting to activate.

unable-resolve-service-type-attempting-activate

This is because the ASP .NET dependency injection container does not know about which object instance to provide if someone requests an object that implements IEmployeeRepository.

For Now To fix the InvalidOperationException error, we need to register MockEmployeeRepository class with the dependency injection container in ASP.NET core.

We do this in ConfigureServices() method in Startup class

For now, to fix the InvalidOperationException error, let’s register MockEmployeeRepository class with the ASP.NET Core Dependency Injection container using AddSingleton() method as shown below. So, with this code in-place, if someone asks for IEmployeeRepository, an instance of MockEmployeeRepository will be provided.

Unable to resolve service for type while attempting to activate

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //Add this line after that run the project. you will not get any error 
            //like, Unable to resolve service for type while attempting to activate
            services.AddSingleton<IEmployeeRepostory, MocEmployeeRepository>();
        }

Leave a Reply

Your email address will not be published. Required fields are marked *