0

I try to add migration in my EF Core 5 project. All entities are set up well. Unfortunately when I do add-migration InitialMigration then the following error occurs:

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[TicketManagement.Application.Features.Events.Commands.CreateEvent.CreateEventCommand,System.Guid] Lifetime: Transient ImplementationType: TicketManagement.Application.Features.Events.Commands.CreateEvent.CreateEventCommandHandler': Unable to resolve service for type 'TicketManagement.Application.Models.Mail.EmailSettings' while attempting to activate 'TicketManagement.Infrastructure.Mail.EmailService'.) (Error while validating the service descriptor 'ServiceType: TicketManagement.Application.Contracts.Infrastructure.IEmailService Lifetime: Transient ImplementationType: TicketManagement.Infrastructure.Mail.EmailService': Unable to resolve service for type 'TicketManagement.Application.Models.Mail.EmailSettings' while attempting to activate 'TicketManagement.Infrastructure.Mail.EmailService'.)

I added all services to Startup.cs class.

public void ConfigureServices(IServiceCollection services)
  {
     services.AddApplicationServices();
     services.AddPersistenceServices(Configuration);
     services.AddInfrastructureServices(Configuration);
     services.AddControllers();

     services.AddSwaggerGen(c =>
         {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "TicketManagement.Api", Version = "v1" });
      });

     services.AddCors(options =>
          {
             options.AddPolicy("Open", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
          });
}

WHat's the root cause of this kind of error?

mustafa00
  • 751
  • 1
  • 7
  • 28
  • 1
    And where `EmailSettings` are registered? – Guru Stron Jan 16 '23 at 14:00
  • Does this answer your question? [An error occurred while accessing the Microsoft.Extensions.Hosting services when do first migrations](https://stackoverflow.com/questions/60561851/an-error-occurred-while-accessing-the-microsoft-extensions-hosting-services-when) – David Jones Jan 16 '23 at 14:02
  • Guys, I didn't retrieve configured options from `EmailSettings`, that was a problem. Thanks for help – mustafa00 Jan 16 '23 at 14:27

1 Answers1

1

You need to add EmailSettings to the service collection as EmailService does not know how to resolve the service.

Haukland
  • 677
  • 8
  • 25
  • 1
    I added it to service collection: `services.Configure(configuration.GetSection("EmailSettings"));` , `services.AddTransient();`. The issue was I forgot to retrieve configured EmailSettings instances using IOptions interface. Now it's ok. Thanks for your hints, it helped a lot. – mustafa00 Jan 16 '23 at 14:26