How to cache HttpClients using a Windows Service + AutoFac registration?

52 views Asked by At

I am writing a Windows Service App using the .NET Framework 4.8. I am using Autofac to register various classes that will be used by the service. The Autofac initializer sets up these objects within a container. One of these is an IHttpClientFactory.CreateClient method. the problem I am having is not knowing how to cache the HttpClient configuration which typically I see in an IServicesCollection. I will explain using my code

public class AutofacConfig
{
    public static IContainer container { get; private set; }

    public const string ApiClientName = "TheApiClient";
    public static void Initialize()
    {
        var builder = new ContainerBuilder();
        SetupServices(builder);
    }

    private static void SetupServices(ContainerBuilder builder)
    {
        builder.Register(r => r.Resolve<IHttpClientFactory>()
        .CreateClient(ApiClientName))
        .Keyed<HttpClient>(ApiClientName)
        .InstancePerLifetimeScope();

        builder.Register<IApiInvokerService>(r =>
            new ApiInvokerService(r.ResolveKeyed<HttpClient>(ApiClientName)))
            .InstancePerLifetimeScope();
    }
}

}

Accordingly, whenever an instance of IApiInvokerService is created, it will be injected with an instance of a HttpClient configured according to that named "TheApiClient". If I had access to an IServiceCollection (as is the case in a startup.cs file) I could add that configuration as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient(...);
}

if it is possible to do this, where would I put the code to cache the HttpClient configuration?

Here is the code for the service:

public partial class MyService : ServiceBase
{
    public MyService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        using (var scope = AutofacConfig.container.BeginLifetimeScope())
        {
            var apisvc = scope.Resolve<IApiInvokerService>();
            apisvc.Invoke();
        }
    }

    protected override void OnStop()
    {
    }
}

Here is the code for the program.cs file

static class Program
{
    static void Main()
    {
        AutofacConfig.Initialize();

        using (var scope = AutofacConfig.container.BeginLifetimeScope())
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
            new MyService()
            };
            ServiceBase.Run(ServicesToRun); 
        }
    }
}

I thank you in advance for any assistance you can offer.

0

There are 0 answers