5

I'm in the process of migrating a .Net Core 1.x project to .Net Core 2.0. One of the things that has changed is that Authentication is now configured in ConfigureServices during startup using extensions to IServiceCollection.

I have some custom services which are used in my authentication schemes, however the bulk of the DI registration is built using AutoFac (after this is called):

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    //Other .Net Services Registered
    services.AddTransient<ITicketStore, DistributedCacheTicketStore>(); 
    services.AddSingleton<AuthenticationEvents>();  

    var sp = services.BuildServiceProvider();

    services.AddAuthentication()
        .AddCookie(options =>
        {
            //Other cookie options
            options.SessionStore = sp.GetService<ITicketStore>();
        })
        .AddOpenIdConnect(options =>
        {
            //Other OIDC options
            options.Events = sp.GetService<AuthenticationEvents>();
        });

    //Register application services with AutoFac
    var builder = new ContainerBuilder();
    RegisterAutoFacTypes(builder);

    //Include services from .Net DI container
    builder.Populate(services);

    //Build and return the AutoFac container
    var container = builder.Build();
    return container.Resolve<IServiceProvider>();
}

At the moment, I'm attempting to also register the dependencies of DistributedCacheTicketStore and AuthenticationEvents on the IServiceCollection to allow me to use them in my Authentication config, but this is getting messy and I'd much rather keep it in the AutoFac registration.

Is there a sensible way of refactoring this to keep these registrations in AutoFac, but still use services.AddAuthentication() before the AutoFac container is built?

TallMcPaul
  • 586
  • 1
  • 9
  • 18
  • For anyone else struggling with this answer, see https://stackoverflow.com/a/47036122/977554 – Dave Dec 26 '19 at 20:14

0 Answers0