Accesing Application DI Container in Configure Services

329 Views Asked by At

With .net core 3 and above ConfigureServices method doesn't return IServiceprovider. We used to configure Autofac in the ConfigureServices method and use it to resolve the registered proxies for our Controllers so that we could add the controllers as services:

 public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        var builder = new ContainerBuilder();

        services.AddHttpClient();

        var mvcBuilder = services.AddMvc(
                o =>
                {
                    o.Filters.Add<ModelStateValidationFilter>(1);
                    o.Filters.Add<RequestLogActionFilter>(int.MinValue);
                }).AddMvcOptions(o => o.EnableEndpointRouting = false)
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            
        builder.Populate(services);

        builder.RegisterModule(_module);

        builder.RegisterModule<DiagnosticsModule>();
        
        ApplicationContainer = builder.Build();

        mvcBuilder.AddControllersAsServices().AddGeneratedControllerProxies(ApplicationContainer);

        return new AutofacServiceProvider(ApplicationContainer);
    }

AddGeneratedControllerProxies extension method looks like:

public static IMvcBuilder AddGeneratedControllerProxies(this IMvcBuilder builder, IContainer applicationContainer)
        => builder.ConfigureApplicationPartManager(
            m => m.FeatureProviders.Add(new ControllerProxyFeatureProvider(applicationContainer.ResolveOptional<IEnumerable<ControllerRegistration>>())));

Now since the DI service provider factory is configured differently in .net core 3+ and above, a new method ConfigureContainer is called at runtime where we register our modules and types. I would like to resolve my controller proxies in the ConfigureServices method but I don't have access to the Container, is there anything I can do to achieve that?

0

There are 0 best solutions below