使用ASP .NET Core 2.0从Main访问服务

时间:2017-12-13 16:00:35

标签: c# asp.net-core

我正在尝试访问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();
    }
}

1 个答案:

答案 0 :(得分:2)

您尚未注册RegisterService,但您已注册IRegisterService。您专门询问RegisterService的实例,该实例无法解决。你需要:

  1. 添加RegisterService本身:

    services.AddTransient<RegisterService>();
    
  2. -OR -

    1. 请求IRegisterService

      var registerService = services.GetRequiredService<IRegisterService>();