[英]System.ArgumentNullException: 'Value cannot be null. Parameter name: items'
[英]{"Value cannot be null. (Parameter 'connectionString')"} System.ArgumentNullException in Blazor Webassembly project
在我的项目中,connectionString 在运行时会引发 null 指针异常,即使它配置正确。
appsettings.json
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-<DATABASE_NAME>;Trusted_Connection=True;MultipleActiveResultSets=true",
"CustomConnection": "Server=(localdb)\\mssqllocaldb;Database=<DATABASE_NAME>"
}
启动.cs
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
我在这里能错过什么? 提前致谢。
ApplicationDbContext.cs
using IdentityServer4.EntityFramework.Options;
using Microsoft.AspNetCore.ApiAuthorization.IdentityServer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using App.Models;
using App.Shared;
namespace App.Server.Data
{
public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
{
public ApplicationDbContext(
DbContextOptions options,
IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ApplyConfiguration(new RoleConfiguration());
}
}
}
不要使用 EntityFrameworkCore 提供的 AddDbContext 扩展方法,它需要 DbContext 上的标准构造函数,而是直接使用 AddScoped 并提供一个使用自定义参数返回构造的 DbContext 的方法:
改变:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
至:
IOptions<OperationalStoreOptions> osOptions;
services.AddScoped<ApplicationDbContext>(sp =>
{
DbContextOptionsBuilder<ApplicationDbContext> optsBuilder =
new DbContextOptionsBuilder<ApplicationDbContext>()
.UseSqlServer(Configuration.GetConnectionString("DefaultConnection");
// If an instance of osOptions is available at this time
return new ApplicationDbContext(optsBuilder.Options, osOptions);
// Or, if the options are registered in the service container
// then resolve from the service provider
return new ApplicationDbContext(
optsBuilder.Options,
sp.GetRequiredService<IOptions<OperationalStoreOptions>());
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.