runtime: .NET 8.0.0-preview.5.23280.1 and Entity Framework Core can't read appsettings.json during migration

Describe the bug

When running an EF migration: “An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: failed to load configuration from file ‘appsettings.js’”

To Reproduce

.NET MVC project with Entity Framework Core SDK and package versions 8.0.0-preview.5.23280.1 Basic ApplicationDbContext.cs:

using Microsoft.EntityFrameworkCore;

namespace MyApp.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
            
        }
    }
}

Basic appsettings.json: (note that in spite of the error message, appsettings.json is valid and works just fine in other .NET versions)

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "a valid connection string"
  }
}

Basic Program.cs:

using MyApp.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<ApplicationDbContext>(options=>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

And the .csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0-preview.5.23280.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0-preview.5.23280.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0-preview.5.23280.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

</Project>

Exceptions (if any)

PM> Add-Migration Initial -verbose

Using project 'MyApp'.

Using startup project 'MyApp'.

Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile C:\Users\Default\Desktop\MVC\MyApp\bin\Debug\net8.0\MyApp.deps.json --additionalprobingpath C:\Users\Default\.nuget\packages --additionalprobingpath "D:\IDEs\Visual Studio 2022\Shared\NuGetPackages" --runtimeconfig C:\Users\Default\Desktop\MVC\MyApp\bin\Debug\net8.0\MyApp.runtimeconfig.json C:\Users\Default\.nuget\packages\microsoft.entityframeworkcore.tools\8.0.0-preview.5.23280.1\tools\netcoreapp2.0\any\ef.dll migrations add Initial --json --verbose --no-color --prefix-output --assembly C:\Users\Default\Desktop\MVC\MyApp\bin\Debug\net8.0\MyApp.dll --project C:\Users\Default\Desktop\MVC\MyApp\MyApp.csproj --startup-assembly C:\Users\Default\Desktop\MVC\MyApp\bin\Debug\net8.0\MyApp.dll --startup-project C:\Users\Default\Desktop\MVC\MyApp\MyApp.csproj --project-dir C:\Users\Default\Desktop\MVC\MyApp\ --language C# --configuration Debug --working-dir C:\Users\Default\Desktop\MVC --root-namespace MyApp --nullable

Using assembly 'MyApp'.

Using startup assembly 'MyApp'.

Using application base 'C:\Users\Default\Desktop\MVC\MyApp\bin\Debug\net8.0'.

Using working directory 'C:\Users\Default\Desktop\MVC\MyApp'.

Using root namespace 'MyApp'.

Using project directory 'C:\Users\Default\Desktop\MVC\MyApp\'.

Remaining arguments: .

Finding DbContext classes...

Finding IDesignTimeDbContextFactory implementations...

Finding application service provider in assembly 'MyApp'...

Finding Microsoft.Extensions.Hosting service provider...

Using environment 'Development'.

System.IO.InvalidDataException: Failed to load configuration from file 'C:\Users\Default\Desktop\MVC\MyApp\appsettings.json'.

 ---> System.TypeInitializationException: The type initializer for 'System.Text.Json.JsonReaderHelper' threw an exception.

 ---> System.TypeLoadException: Could not load type 'System.Buffers.SearchValues' from assembly 'System.Runtime, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

   at System.Text.Json.JsonReaderHelper..cctor()

   --- End of inner exception stack trace ---

   at System.Text.Json.JsonReaderHelper.GetUtf8ByteCount(ReadOnlySpan`1 text)

   at System.Text.Json.JsonDocument.Parse(ReadOnlyMemory`1 json, JsonDocumentOptions options)

   at System.Text.Json.JsonDocument.Parse(String json, JsonDocumentOptions options)

   at Microsoft.Extensions.Configuration.Json.JsonConfigurationFileParser.ParseStream(Stream input)

   at Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider.Load(Stream stream)

   at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)

   --- End of inner exception stack trace ---

   at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)

   at Microsoft.Extensions.Configuration.ConfigurationManager.AddSource(IConfigurationSource source)

   at Microsoft.Extensions.Configuration.ConfigurationManager.Microsoft.Extensions.Configuration.IConfigurationBuilder.Add(IConfigurationSource source)

   at Microsoft.Extensions.Configuration.ConfigurationExtensions.Add[TSource](IConfigurationBuilder builder, Action`1 configureSource)

   at Microsoft.Extensions.Configuration.JsonConfigurationExtensions.AddJsonFile(IConfigurationBuilder builder, String path, Boolean optional, Boolean reloadOnChange)

   at Microsoft.Extensions.Hosting.HostingHostBuilderExtensions.ApplyDefaultAppConfiguration(HostBuilderContext hostingContext, IConfigurationBuilder appConfigBuilder, String[] args)

   at Microsoft.Extensions.Hosting.HostApplicationBuilder..ctor(HostApplicationBuilderSettings settings)

   at Microsoft.AspNetCore.Builder.WebApplicationBuilder..ctor(WebApplicationOptions options, Action`1 configureDefaults)

   at Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(String[] args)

   at Program.<Main>$(String[] args) in C:\Users\Default\Desktop\MVC\MyApp\Program.cs:line 4

   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)

   at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)

--- End of stack trace from previous location ---

   at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.CreateHost()

   at Microsoft.Extensions.Hosting.HostFactoryResolver.<>c__DisplayClass10_0.<ResolveHostFactory>b__0(String[] args)

   at Microsoft.Extensions.Hosting.HostFactoryResolver.<>c__DisplayClass13_0.<ResolveServiceProviderFactory>b__3(String[] args)

   at Microsoft.EntityFrameworkCore.Design.Internal.AppServiceProviderFactory.CreateFromHosting(String[] args)

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Failed to load configuration from file 'C:\Users\Default\Desktop\MVC\MyApp\appsettings.json'.

No application service provider was found.

Finding DbContext classes in the project...

Found DbContext 'ApplicationDbContext'.

Microsoft.EntityFrameworkCore.Design.OperationException: 

    Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[MyApp.Data.ApplicationDbContext]' while attempting to activate 'MyApp.Data.ApplicationDbContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

 ---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[MyApp.Data.ApplicationDbContext]' while attempting to activate 'MyApp.Data.ApplicationDbContext'.

   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)

   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)

   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)

   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass20_5.<FindContextTypes>b__13()

   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)

   --- End of inner exception stack trace ---

   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)

   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)

   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)

   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()

   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()

   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)



    Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[MyApp.Data.ApplicationDbContext]' while attempting to activate 'MyApp.Data.ApplicationDbContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Further technical details

(Submitting on behalf of errors reported to me, so not 100% sure of the environment)

  • The IDE (VS / VS Code/ VS4Mac) you’re running on, and its version Visual Studio 2022 on Windows

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 26 (10 by maintainers)

Most upvoted comments

Hi, I have the same problem, I just updated to version 8.0.0-preview.5.23280.1 and have the same exception. Waiting for a solution.

Make sure you have the latest SDK installed. Link

@mis2000lab does the preview version of the package match the preview version of the runtime?

Seems like a type load exception when trying to load SearchValues from System.Buffers. Probably a transient issue due to incompatible builds being used? cc @MihaZupan

Same for me, after latest update to preview 5

EDIT: Downloading latest sdk fixed for me! (probably thanks to @marcpopMSFT ) dotnet-sdk-8.0.100-preview.5.23303.2

+1, got this issue on linux, but works on windows