-1

In .net 6 Asp.net Core Startup.cs I have this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DbSeeder dataSeeder)
{
    dataSeeder.Seed();

here the DbSeeder is resolved because I've added it as a parameter to the Configure method.

How would I do the same (resolve a service) in .net 7 if I choose to skip the Startup.cs and have all the configuration in Program.cs ?

buga
  • 852
  • 9
  • 21

1 Answers1

1

There are several ways. This is how I do it.

I have a static class for all my configuration stuff - in this case to add some test data to a InMemory test database

public static class WeatherAppDataServices
{
    // extension method for IServiceCollection 
    public static void AddAppServices(this IServiceCollection services)
    {
       // define your specific services
        services.AddScoped<WeatherForecastService>();
    }

    //.... other config stuff

    public static void AddTestData(IServiceProvider provider)
    {
        var factory = provider.GetService<IDbContextFactory<InMemoryWeatherDbContext>>();

        if (factory is not null)
            // do your seeding
            // this one is mine
            WeatherTestDataProvider.Instance().LoadDbContext<InMemoryWeatherDbContext>(factory);
    }
}

And my Program:

// Add services to the container.
{
    var Services = builder.Services;
    {
        Services.AddRazorPages();
        Services.AddServerSideBlazor();
        Services.AddControllersWithViews();

        Services.AddAuthentication();
        Services.AddAuthorization();

        // this is where my specific app services get added
        Services.AddAppServices();

        Services.AddWeatherAppServerDataServices<InMemoryWeatherDbContext>(options
            => options.UseInMemoryDatabase($"WeatherDatabase-{Guid.NewGuid().ToString()}"));
      /....
    }
}

var app = builder.Build();

// you now have a `WebApplication` instance and can get the services manually
// I Add the test data to the In Memory Db here
WeatherAppDataServices.AddTestData(app.Services);

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
/....
MrC aka Shaun Curtis
  • 19,075
  • 3
  • 13
  • 31
  • 3
    think a shorter answer would be `var app = builder.Build(); var neededServ = app.Services.GetService();` – buga Nov 23 '22 at 09:27