Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptionsBuilder`

Viewed 345

When I am injecting DbContextOptionsBuilder to CustomTicketStore in ASP.NET core 3.1. I am getting an exception message

Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Authentication.Cookies.ITicketStore Lifetime: Scoped ImplementationType: OneIAM.Services.CustomTicketStore': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptionsBuilder`1[OneIAM.Data.ApplicationDbContext]' while attempting to activate 'OneIAM.Services.CustomTicketStore'.)

Below is code from the Startup file.

        public virtual void ConfigureServices(IServiceCollection services)
        {
          ...

          // Persistent ticket/cookie store to provide durable user sessions
          services.AddScoped<ITicketStore, CustomTicketStore>();
          var optionsBuilder = GetDbContextOptionsBuilder(services);

          services.ConfigureApplicationCookie(options =>
          {
            options.SlidingExpiration = true;
            options.SessionStore = new CustomTicketStore(optionsBuilder);  <=
          });
        }

        private static DbContextOptionsBuilder<ApplicationDbContext> GetDbContextOptionsBuilder(IServiceCollection services)
        {
            using (var scope = services.BuildServiceProvider().CreateScope())
            {
                return scope.ServiceProvider.GetService<DbContextOptionsBuilder<ApplicationDbContext>>();
            }
        }
1 Answers

Firstly,I test your code,and find it will reproduce your error with services.AddScoped<ITicketStore, CustomTicketStore>(); And here is my CustomTicketStore:

public class CustomTicketStore: ITicketStore
    {
        private readonly DbContextOptionsBuilder<ApplicationDbContext> _optionsBuilder;
        

        public CustomTicketStore(DbContextOptionsBuilder<ApplicationDbContext> optionsBuilder)
        {
            _optionsBuilder = optionsBuilder;
        }

        .......
    }

And I find if I add a constructor without parameters to CustomTicketStore,it will work:

public class CustomTicketStore: ITicketStore
    {
        private readonly DbContextOptionsBuilder<ApplicationDbContext> _optionsBuilder;
        public CustomTicketStore()
        {
        }

        public CustomTicketStore(DbContextOptionsBuilder<ApplicationDbContext> optionsBuilder)
        {
            _optionsBuilder = optionsBuilder;
        }

        ........
    }
Related