0

I upgraded my Blazor server project to .Net 8 and get this error:

     System.AggregateException: 'Some services are not able to be constructed'
        
            TypeLoadException: Could not load type 
    
    'System.Runtime.CompilerServices.NullableAttribute' from assembly 'System.Runtime, 
    
    Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

    InvalidOperationException: Error while validating the service descriptor 'ServiceType: 

Microsoft.Extensions.Hosting.IHostApplicationLifetime Lifetime: Singleton ImplementationType: 

Microsoft.Extensions.Hosting.Internal.ApplicationLifetime': 

Could not load type 'System.Runtime.CompilerServices.NullableAttribute' from assembly 'System.Runtime, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

I also commented out Nullable in edit project so that Nullable reference types are disabled.

What is this error and how to correct this?

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

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

  <ItemGroup>
    <None Include="Pages\Counter.razor" />
    <None Include="Pages\Error.cshtml" />
    <None Include="Pages\Index.razor" />
    <None Include="Pages\_Host.cshtml" />
    <None Include="Shared\MainLayout.razor" />
    <None Include="Shared\NavMenu.razor" />
    <None Include="wwwroot\css\bootstrap\bootstrap.min.css.map" />
    <None Include="wwwroot\css\open-iconic\FONT-LICENSE" />
    <None Include="wwwroot\css\open-iconic\font\fonts\open-iconic.svg" />
    <None Include="wwwroot\css\open-iconic\ICON-LICENSE" />
    <None Include="wwwroot\css\open-iconic\README.md" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Blazor-ApexCharts" Version="0.9.21-beta" />
    <PackageReference Include="Blazor.PersianDatePicker" Version="3.0.2" />
    <PackageReference Include="FreeSpire.PDF" Version="8.6.0" />
    <PackageReference Include="FreeSpire.XLS" Version="12.7.0" />
    <PackageReference Include="HtmlAgilityPack" Version="1.11.51" />
    <PackageReference Include="HtmlSanitizer" Version="8.0.692" />
    <PackageReference Include="LinqKit.Core" Version="1.2.4" />
    <PackageReference Include="Microsoft.AspNetCore.Components.QuickGrid" Version="8.0.0-preview.7.23375.9" />
    <PackageReference Include="Microsoft.AspNetCore.Components.QuickGrid.EntityFrameworkAdapter" Version="8.0.0-preview.7.23375.9" />
    <PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="8.0.0-preview.7.23375.9" />
    <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0-preview.7.23375.9" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="7.0.10" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0-preview.7.23375.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0-preview.7.23375.4">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0-preview.7.23375.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite" Version="8.0.0-preview.7.23375.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0-preview.7.23375.4">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Identity.Core" Version="8.0.0-preview.7.23375.9" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0-preview.7.23375.6" />
    <PackageReference Include="Microsoft.Spatial" Version="7.17.0" />
    <PackageReference Include="MW.Blazor.TagSelector" Version="1.2.3" />
    <PackageReference Include="MW.Blazor.Tree" Version="1.3.0" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageReference Include="SbSelect" Version="2.0.5" />
    <PackageReference Include="System.Drawing.Common" Version="8.0.0-preview.7.23375.5" />
    <PackageReference Include="System.Linq.Dynamic.Core" Version="1.3.4" />
    <PackageReference Include="TinyMCE.Blazor" Version="1.0.4" />
  </ItemGroup>

</Project>

Program.cs:

//-------------------------------------------- Services -----------------------------------------------------
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
//-----------------------------------------------------------------------------------------------------------
services.AddControllersWithViews();
services.AddRazorPages()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
    options => options.ResourcesPath = "Resources")
              .AddDataAnnotationsLocalization(options =>
              {
                  options.DataAnnotationLocalizerProvider = (type, factory) =>
                  {
                      var assemblyName = new AssemblyName(typeof(ClientResource).GetTypeInfo().Assembly.FullName);
                      return factory.Create("SharedResource", assemblyName.Name);
                  };
              });

services.AddServerSideBlazor(options =>
{
    options.JSInteropDefaultCallTimeout = TimeSpan.FromSeconds(15);
}).AddHubOptions(o => o.MaximumReceiveMessageSize = 1000 * 1024 * 1024)
.AddCircuitOptions(opts => opts.DetailedErrors = true);
//services.AddSingleton<WeatherForecastService>();

//services.AddStorage();

string appConnectionString = builder.Configuration.GetConnectionString("AppConnection");
string identityConnectionString = builder.Configuration.GetConnectionString("IdentityConnection");

services.AddDbContextFactory<AppDbContext>(options =>
options.UseSqlServer(appConnectionString,
                x => { x.UseNetTopologySuite(); }), ServiceLifetime.Transient);

services.AddDbContextFactory<IdentityContext>(options =>
    options.UseSqlServer(identityConnectionString), ServiceLifetime.Transient);

services.AddIdentity<AppUser, IdentityRole>(opts =>
{
    opts.User.RequireUniqueEmail = true;
    //opts.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz";
    opts.Password.RequiredLength = 6;
    opts.Password.RequireNonAlphanumeric = false;
    opts.Password.RequireLowercase = false;
    opts.Password.RequireUppercase = false;
    opts.Password.RequireDigit = false;
    opts.ClaimsIdentity.UserIdClaimType = JwtRegisteredClaimNames.Sub; //commented      
    /*opts.Tokens.EmailConfirmationTokenProvider = "custom";*/
    opts.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider;
    opts.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider;
}).AddEntityFrameworkStores<IdentityContext>().AddDefaultTokenProviders()
.AddTokenProvider<DataProtectorTokenProvider<AppUser>>("custom").AddDefaultUI();

//services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo( @$"{env.WebRootPath}\config"));

services.AddLocalization(options => options.ResourcesPath = "Resources");
var supportedCultures = new List<CultureInfo> { new CultureInfo("fa"), new CultureInfo("en"), new CultureInfo("ar") };
services.Configure<RequestLocalizationOptions>(options =>
{
    options.DefaultRequestCulture = new RequestCulture("fa");
    options.SupportedUICultures = supportedCultures;
    options.SupportedCultures = supportedCultures;
    options.RequestCultureProviders.Add(new CookieRequestCultureProvider() { CookieName = "RP" });
});

//services.AddSyncfusionBlazor(false);

services.AddHttpContextAccessor();
services.AddScoped<IJsInterop, JsInterop>();
services.AddScoped<ViewDataService>();
services.AddScoped<TextService>();
services.AddScoped<TextService2>();
services.AddScoped<CultureChanger>();
services.AddTransient<Account>();
services.AddTransient<Admin>();
services.AddTransient<Home>();
services.AddTransient<HttpClient>();
//services.AddProtectedBrowserStorage();
services.AddScoped<MZScopedSessionID>();
services.AddSingleton<MZSingleton<Cart>>();
services.AddScoped<MZScoped<Cart>>();
services.AddSingleton<MZSingleton<IsAuthenticatedModel>>();
services.AddScoped<MZScoped<IsAuthenticatedModel>>();
services.AddScoped<IService, Service>();
services.AddTransient<JsConsole>();
services.AddScoped<IEmailSender, EmailSender>();
services.AddScoped<LocService>();
services.AddQuickGridEntityFrameworkAdapter();


services.AddMemoryCache();
services.AddSession();


//services.AddAntDesign();

/****************************** Create Admin Account ***************************/
//IdentityContext.CreateAdminAccount(services.BuildServiceProvider(), builder.Configuration);
/*******************************************************************************/

services.AddHttpsRedirection(options =>
{
    options.RedirectStatusCode = (int)HttpStatusCode.PermanentRedirect;
    options.HttpsPort = 443;
});


//---------------------------------------------- Configuration ----------------------------------------------
var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/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.UseStaticFiles();
app.UseHttpsRedirection();

//app.UsePathBase("/store");

app.UseSession();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapControllerRoute("controllers", "controllers/{controller=Site}/{action=Index}/{id?}");
app.MapRazorPages();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

//-----------------------------------------------------------------------------------------------------------
app.Run();
//-------------------

I tried to disable almost all services registrations, but get the same error.

mz1378
  • 1,957
  • 4
  • 20
  • 40

1 Answers1

1

I had the same issue and tracked it down to:

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0-preview.7.23375.4" />

I downgraded to the previous preview release and it resolved the issue for me.

Ben Smith
  • 26
  • 1