Quoting documentation
Services Available in Startup
ASP.NET Core dependency injection provides application services during
an application’s startup. You can request these services by including
the appropriate interface as a parameter on yourStartupclass’s
constructor or one of itsConfigureorConfigureServicesmethods.Looking at each method in the
Startupclass in the order in which
they are called, the following services may be requested as
parameters:
- In the constructor:
IHostingEnvironment,ILoggerFactory- In the
ConfigureServicesmethod:IServiceCollection- In the
Configuremethod:IApplicationBuilder,IHostingEnvironment,
ILoggerFactory,IApplicationLifetime
You are trying to resolve services that are not available during startup,
...CommunicatorContext dbContext, ILdapService ldapService) {
which will give you the errors you are getting. If you need access to the implementations then you need to do one of the following:
-
Modify the
ConfigureServicesmethod and access them there from the service collection. i.e.public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddDbContext<CommunicatorContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddCookieAuthentication(); services.Configure<LdapConfig>(Configuration.GetSection("Ldap")); services.AddScoped<ILdapService, LdapService>(); services.AddMvc(); // Build the intermediate service provider var serviceProvider = services.BuildServiceProvider(); //resolve implementations var dbContext = serviceProvider.GetService<CommunicatorContext>(); var ldapService = serviceProvider.GetService<ILdapService>(); DbInitializer.Initialize(dbContext, ldapService); //return the provider return serviceProvider(); } -
Modify the
ConfigureServicesmethod to return IServiceProvider,Configuremethod to take aIServiceProviderand then resolve your dependencies there. i.e.public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddDbContext<CommunicatorContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddCookieAuthentication(); services.Configure<LdapConfig>(Configuration.GetSection("Ldap")); services.AddScoped<ILdapService, LdapService>(); services.AddMvc(); // Build the intermediate service provider then return it return services.BuildServiceProvider(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider) { //...Other code removed for brevity app.UseMvc(); //resolve dependencies var dbContext = serviceProvider.GetService<CommunicatorContext>(); var ldapService = serviceProvider.GetService<ILdapService>(); DbInitializer.Initialize(dbContext, ldapService); }