I had a 1.0 project that I was upgrading to 2.0. I followed the migration guide found here: https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/ -- the part of interest here is the bit about the CreateScope
and the Move database initialization code
. Seems as though this doesn't work as intended.
Even when creating a new project with dotnet new webApi
and using dotnet restore
and putting this code:
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
// Requires using RazorPagesMovie.Models;
SeedData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
host.Run();
in the Main
function and trying to run it I get this error:
Program.cs(13,37): error CS1061: 'IServiceProvider' does not contain a definition for 'CreateScope' and no extension method 'CreateScope' accepting a first argument of type 'IServiceProvider' could be found (are you missing a using directive or an assembly reference?)
This seems like a pretty obvious issue that could be resolved. Seems strange that this code in the migration guide doesn't work in a 2.0 project built right out of the box? The CreateScope
is simply not on the interface in question via host.Services
.
It's an extension method.
https://github.com/aspnet/DependencyInjection/blob/88c3bd6fe2786dd759b4a6c6d7c410e895336b6c/src/DI.Abstractions/ServiceProviderServiceExtensions.cs#L125
Add using Microsoft.Extensions.DependencyInjection;
Ah, right you are. I sorted it now, thanks!
Most helpful comment
It's an extension method.
https://github.com/aspnet/DependencyInjection/blob/88c3bd6fe2786dd759b4a6c6d7c410e895336b6c/src/DI.Abstractions/ServiceProviderServiceExtensions.cs#L125
Add
using Microsoft.Extensions.DependencyInjection;