Resolve keyed dependency for BackgroudService

Viewed 27

I am using the BackgroundService found in .NET 6.

I am creating my IHost as below:

IHost host = Host.CreateDefaultBuilder(args)
    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
    })
    .ConfigureContainer<ContainerBuilder>(autofacConfigure =>
    {
        autofacConfigure.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            .Where(t => t.GetInterfaces().Contains(typeof(IInterface)) &&
                        t.GetCustomAttribute<KeyIdAttribute>() != null)
            .Keyed<IInterface>(t => t.GetCustomAttribute<KeyIdAttribute>().KeyId);
    })
    .UseSerilog((ctx,lc) => lc
        .ReadFrom.Configuration(ctx.Configuration))
    .Build();

My BackgroundService takes an IInterface as a constructor parameter. How can should the IInterface be resolved based on the KeyId (passed in) before the constructor is called?

Thank you.

0 Answers
Related