I receive following exception when I try to use custom DbContext in Configure method in Startup.cs file. I use ASP.NET Core in version 2.0.0-previe
The solution from NKosi works because by invoking services.BuildServiceProvider() yourself without parameters you are not passing the validateScopes. Because this validation is disabled, the exception is not thrown. This doesn't mean that the problem is not there.
EF Core DbContext is registered with a scoped lifestyle. In ASP native DI, the container scope is connected to instance of IServiceProvider. Normally, when you use your DbContext from a Controller there is no problem because ASP creates a new scope (new instance of IServiceProvider) for each request and then uses it to resolve everything within this request. However during the application startup you don't have request scope. You have an instance of IServiceProvider that is not scoped (or in other words in root scope). This means you should create a scope yourself. You can do it like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var scopeFactory = app.ApplicationServices.GetRequiredService();
using (var scope = scopeFactory.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService();
var ldapService = scope.ServiceProvider.GetRequiredService();
// rest of your code
}
// rest of Configure setup
}
The ConfigureServices method can remain unchanged.
EDIT
Your solution will work in 2.0.0 RTM without any changes since in RTM scoped service provider will be created for Configure method https://github.com/aspnet/Hosting/pull/1106.