Home > OS >  Resolve service in Program.cs .net 7 Asp.net Core
Resolve service in Program.cs .net 7 Asp.net Core

Time:11-24

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 ?

CodePudding user response:

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())
/....
  • Related