我正在尝试访问DbInitializer
中的服务。我得到ApplicationDbContext
没有任何问题,但我收到RegisterService
的以下错误:
没有“Shared.Services.RegisterService”类型的服务 注册
以下是代码:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddEntityFrameworkSqlServer().AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"], sqlOptions => { })
);
services.AddTransient<IRegisterService, RegisterService>();
services.AddTransient<IEmailService, EmailService>();
services.AddMvc();
}
public class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
MainAsync(services).GetAwaiter().GetResult();
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating the database.");
}
}
host.Run();
}
public static async Task MainAsync(IServiceProvider services)
{
await DbInitializer.Initialize(services);
}
}
public class DbInitializer
{
public static async Task Initialize(IServiceProvider services)
{
var context = services.GetRequiredService<ApplicationDbContext>();
var registerService = services.GetRequiredService<RegisterService>();
context.Database.EnsureCreated();
}
}
答案 0 :(得分:2)
您尚未注册RegisterService
,但您已注册IRegisterService
。您专门询问RegisterService
的实例,该实例无法解决。你需要:
添加RegisterService
本身:
services.AddTransient<RegisterService>();
-OR -
请求IRegisterService
:
var registerService = services.GetRequiredService<IRegisterService>();