2

I'm trying to access services in my DbInitializer. I get ApplicationDbContext without any problems, but I get the following error for RegisterService:

No service for type 'Shared.Services.RegisterService' has been registered.

Here is the code:

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();
    }
}
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Primico
  • 2,143
  • 3
  • 24
  • 36

1 Answers1

3

You haven't actually registered RegisterService, you've registered IRegisterService. You're asking specifically for an instance of RegisterService, which is not going to resolve. You need to either:

  1. Add RegisterService itself:

    services.AddTransient<RegisterService>();
    

-or-

  1. Request IRegisterService instead:

    var registerService = services.GetRequiredService<IRegisterService>();
    
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203