ejacobg / eShopOnContainers

A reference project for when I forget how to do something.
MIT License
0 stars 0 forks source link

Convert Autofac -> Microsoft.Extensions.DependencyInjection #2

Closed ejacobg closed 3 months ago

ejacobg commented 3 months ago

I don't care about using Autofac right now.

From the Catalog API's Startup.cs :

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddAppInsight(Configuration)
        .AddGrpc().Services
        .AddCustomMVC(Configuration)
        .AddCustomDbContext(Configuration)
        .AddCustomOptions(Configuration)
        .AddIntegrationServices(Configuration)
        .AddEventBus(Configuration)
        .AddSwagger(Configuration)
        .AddCustomHealthCheck(Configuration);

    var container = new ContainerBuilder();
    container.Populate(services);

    return new AutofacServiceProvider(container.Build());
}

Related: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.istartup.configureservices?view=aspnetcore-8.0

Is this even correct usage of Autofac? The documentation seems to discourage doing this.

Don't build or return any IServiceProvider or the ConfigureContainer method won't get called. Don't create a ContainerBuilder for Autofac here, and don't call builder.Populate() - that happens in the AutofacServiceProviderFactory for you.

ejacobg commented 3 months ago

ChatGPT says returning void will have the runtime use the built-in DI container instead?

public void ConfigureServices(IServiceCollection services)
{
    services.AddAppInsight(Configuration)
        .AddGrpc().Services
        .AddCustomMVC(Configuration)
        .AddCustomDbContext(Configuration)
        .AddCustomOptions(Configuration)
        .AddIntegrationServices(Configuration)
        .AddEventBus(Configuration)
        .AddSwagger(Configuration)
        .AddCustomHealthCheck(Configuration);
}

Further reading: