[英]No service for type 'Type' has been registered
I have a database context that I am registering and seeding.我有一个正在注册和播种的数据库上下文。 However, I get the error:
但是,我收到错误:
System.InvalidOperationException: 'No service for type 'AnnouncementContext' has been registered.'
System.InvalidOperationException:“没有注册‘AnnouncementContext’类型的服务。”
DB registering/seeding数据库注册/播种
private static void SeedDatabase(IHost host)
{
var scopeFactory = host.Services.GetRequiredService<IServiceScopeFactory>();
using var scope = scopeFactory.CreateScope();
var announcementContext = scope.ServiceProvider.GetRequiredService<AnnouncementContext>(); // exception occurs here
if (announcementContext.Database.EnsureCreated()) {
try {
SeedData.Initialize(announcementContext);
}
catch (Exception ex) {
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "A database seeding error occurred.");
ErrorLogger.logError(ex);
}
}
}
Context class上下文 class
public class AnnouncementContext : DbContext {
public AnnouncementContext(DbContextOptions<AnnouncementContext> options)
: base(options) {
}
public DbSet<Announcement> Announcements { get; set; }
}
What is causing this error and how can I fix it?是什么导致了这个错误,我该如何解决?
The code in your DB registering/seeding
section is not registering any DB or DbContext. DB registering/seeding
部分中的代码未注册任何数据库或 DbContext。 It is trying to get a reference of already registered DbContext (in your case AnnouncementContext
).它正在尝试获取已注册 DbContext 的引用(在您的情况下为
AnnouncementContext
)。 So, the question is, have you already registered it?那么,问题来了,你注册了吗? The error message indicates, you have not.
错误消息表明,您还没有。
In most common scenario, you are supposed to register the AnnouncementContext
in the ConfigureServices()
method of the Startup
class like -在大多数常见情况下,您应该在
Startup
class 的ConfigureServices()
方法中注册AnnouncementContext
,例如 -
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// this is the DbContext registration code
services.AddDbContext<AnnouncementContext>(
options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
}
For more on this - DbContext in dependency injection for ASP.NET Core有关此的更多信息 - DbContext in dependency injection for ASP.NET Core
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.