InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor'

I started to convert my asp.net core RC1 project to RC2 and faced with problem that now IHttpContextAccessordoes not resolved.

For sake of simplicity I created new ASP.NET RC2 project using Visual Studio Template ASP.NET Core Web Application (.Net Framework). Than I added constructor for HomeController which template created for me.

public HomeController(IHttpContextAccessor accessor)
{
}

And after I start application I receive next error:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'TestNewCore.Controllers.HomeController'. в Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)

In my real application I need to resolve IHttpContextAccessor in my own service class for getting access to _contextAccessor.HttpContext.Authentication and to _contextAccessor.HttpContext.User. Everething works fine in RC1. So how can it suppose to be in RC2?

Score: 162
Tags: .net, dependency-injection, asp.net-core
Views: 77594
Date posted: 5/22/2016

Unable to resolve service for type 'System.String' while attempting to activate 'MyService'

I'm seeing the following exception in my Service Fabric Stateless ASP.NET Core app.

System.InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate 'MyService'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider provider, ISet`1 callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetResolveCallSite(IService service, ISet`1 callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetServiceCallSite(Type serviceType, ISet`1 callSiteChain)

How can it not be able to resolve System.String? How do I debug this further?

Score: 28
Tags: asp.net-core, dependency-injection, .net-core, azure-service-fabric
Views: 19912
Date posted: 4/13/2018

Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider'

I am starting a new Core Web API, and would like to add Swagger to my application.

My current environment:

  • .Net Core 3.0
  • Swashbuckle.AspNetCore 5.0.0-rc4

Here is my Startup.cs class and configuration:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        //AK: Enable CORS
        //CORS should be configured on host server.
        services.AddCors(setupAction =>
        {
            setupAction.AddPolicy(DevCorsPolicyName,
                builder =>
                {
                    builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
                });
        });

        #region Configuration

        //Configuration File
        services.Configure<AppSettingConfiguration>(Configuration.GetSection("AppSettings"));
        //AutoMapper
        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        //Configure Swagger
        services.ConfigureSwaggerGen(c =>
        {
            c.SwaggerDoc("v3", new OpenApiInfo
            {
                Title = "GTrackAPI",
                Version = "v3"
            });
        });

        #endregion

        #region Dependency Injection

        //Database context and repository
        services.AddDbContext<IGTrackContext, GTrackContext>(builder =>
        {
            builder.UseSqlServer(connectionString: Configuration.GetConnectionString("gtrackConnection"), sqlServerOptionsAction: null);
        });
        services.AddScoped<IGTrackRepository, GTrackRepository>();

        //facade layers
        services.AddScoped<IPersonFacade, PersonFacade>();

        //Service layers
        services.AddScoped<IPersonService, PersonService>();

        #endregion
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //Enable development environment only settings
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        //AK: Only allow all origins for development environmnet
        app.UseCors(DevCorsPolicyName);

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "GTrackAPI");
            c.RoutePrefix = string.Empty; //Configures swagger to load at application root
        });

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

When I run my application, I get the following error:

InvalidOperationException: Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider' while attempting to Invoke middleware 'Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware'.

Here is the Stacktrace:

System.InvalidOperationException: Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider' while attempting to Invoke middleware 'Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware'. at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.GetService(IServiceProvider sp, Type type, Type middleware) at lambda_method(Closure , Object , HttpContext , IServiceProvider ) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass4_1.b__2(HttpContext context) at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context, ICorsPolicyProvider corsPolicyProvider) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass4_1.b__2(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

It is pretty clear that I am missing something here, not sure exactly what. Any help would be appreciated.

Score: 8
Tags: c#, asp.net-core, dependency-injection, swagger, asp.net-core-webapi
Views: 9879
Date posted: 11/18/2019

Configure AutoFac in ASP.NET Core 3.0 Preview 5 or higher

Following the AutoFac documentation, I was able to use AutoFac in ASP.NET Core 3.0 Preview 3. ASP.NET Core 3.0 Preview 4 and ASP.NET Core 3.0 Preview 5 introduced breaking changes and AutoFac no longer works. My controller methods return runtime errors.

The differences between ASP.NET Core 3.0 Preview 3 and ASP.NET Core 3.0 Preview 5 in my code is as follows:

IWebHostBuilder -> IHostBuilder

CreateWebHostBuilder -> CreateHostBuilder

WebHost.CreateDefaultBuilder(args) -> Host.CreateDefaultBuilder(args)

public IServiceProvider ConfigureServices(IServiceCollection services)

to

public void ConfigureServices(IServiceCollection services)
System.AggregateException
  HResult=0x80131500
  Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: API.Controllers.CityController Lifetime: Transient ImplementationType: CityController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'CityController'.) (Error while validating the service descriptor 'ServiceType: LocationController Lifetime: Transient ImplementationType: LocationController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'LocationController'.) (Error while validating the service descriptor 'ServiceType: PersonController Lifetime: Transient ImplementationType: PersonController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'PersonController'.) (Error while validating the service descriptor 'ServiceType: SchoolController Lifetime: Transient ImplementationType: SchoolController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'SchoolController'.) (Error while validating the service descriptor 'ServiceType: TestParentController Lifetime: Transient ImplementationType: TestParentController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'TestParentController'.) (Error while validating the service descriptor 'ServiceType: TypeController Lifetime: Transient ImplementationType: TypeController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'TypeController'.)
  Source=Microsoft.Extensions.DependencyInjection
  StackTrace:
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
   at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at API.Program.Main(String[] args) in C:\Projects\FirstResponse\API\Program.cs:line 13

Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: CityController Lifetime: Transient ImplementationType: CityController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'CityController'.

Inner Exception 2:
InvalidOperationException: Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'CityController'.

Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
      webBuilder
        .UseStartup<Startup>()
        .ConfigureLogging((hostingContext, builder) =>
        {
          builder.ClearProviders();
          builder.SetMinimumLevel(LogLevel.Trace);
          builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
          builder.AddConsole();
          builder.AddDebug();
        })
        .UseNLog();
    });

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  services
    .AddCustomOptions(Configuration)
    .AddCors()
    .AddJwtAuthentication()
    .AddHttpClients()
    .AddCustomMVC()
    .AddIIS()
    .AddCaching()
    .AddCustomDbContext(Configuration, Environment)
    .AddSwagger()
    .AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies())
    .AddHealthChecksUI();

  var serviceProvider = services.BuildServiceProvider();

  _appSettings = serviceProvider.GetService<IOptionsSnapshot<AppSettings>>().Value;

  var connectionString = Configuration.GetConnectionString(nameof(FirstResponseContext));

  // Create a Autofac container builder
  var builder = new ContainerBuilder();

  // Read service collection to Autofac
  builder.Populate(services);

  // Use and configure Autofac
  builder.RegisterModule(new MediatorModule());
  builder.RegisterModule(new ApplicationModule(connectionString));

  // build the Autofac container
  ApplicationContainer = builder.Build();

  // creating the IServiceProvider out of the Autofac container
  //return new AutofacServiceProvider(ApplicationContainer);
}

ApplicationModule.cs

protected override void Load(ContainerBuilder builder)
{
  builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
  builder.RegisterType<ModelValidationAttribute>().InstancePerLifetimeScope();
  builder.RegisterType<ETagCache>().InstancePerLifetimeScope();

  builder.RegisterType<FirstResponseContext>().As<DbContext>().As<IUnitOfWork>().InstancePerLifetimeScope();
}
Score: 6
Tags: c#, asp.net, dependency-injection, autofac, autofac-configuration
Views: 7823
Date posted: 5/30/2019

Unable to resolve service for type in ApplicationDbContext

When I'm trying to add migrations with dnx ef migrations add Mig, I have the following exception in console:

Unable to resolve service for type 'Microsoft.AspNet.Http.IHttpContextAcccessor' while attempting to activate 'NewLibrary.Models.ApplicationDbContext'.

My ApplicationDbContext:

public class ApplicationDbContext : DbContext
{
    private readonly IHttpContextAccessor _accessor;

    public ApplicationDbContext(IHttpContextAccessor accessor)
    {
        _accessor = accessor;
    }
}

What's the problem?

How should I correctly add dependencies to ApplicationDbContext constructor?

Score: 6
Tags: c#, asp.net-core, entity-framework-core
Views: 10715
Date posted: 4/25/2016


2


© 2021 Search Overflow
Contributions licensed under cc by-sa