Search code examples
c#asp.net-web-api2autofac.net-4.8

Pass HttpClient to class library


I have an order management system which sends emails via an external system. The external system is accessed via http calls. The order management has mainly 3 projects: a class library, web api2, and mvc app. In the class library thats where the service for interacting with email system resides. I have wired up all my dependencies using Autofac. I am thinking of creating the httpclient in the web api project so that it gets passed down to the class library. In ASP.NET core its possible but I am not sure of how to do it in .net 4.8.

For context the scenario is as follows: User will place orders using the mvc app which calls the web api. The web api just provides endpoints for all the logic in the class library. When a user places an order they are supposed to receive an email with the order details. The class library calls an external system to send the email. The class library have an interface called IMessagingService which has one method SendEmailAsync. The implementation of this service MessagingService is the one requiring an httpclient

IMessagingService:

public interface IMessagingService
{
    Task SendEmailAsync(string email, string message);

}

Messaging Service:

public class MessagingService : IMessagingService
{
    private readonly HttpClient _httpClient;

    public MessagingService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task SendEmailAsync(string email, string message)
    {
       await _httpClient.PostAsJsonAsync(/*content*/);
    }
}

Web API Global.asax.cs:

public class WebApiApplication : System.Web.HttpApplication
{
    internal static HttpClient _httpClient;

    protected void Application_Start()
    {
        //Removed other lines

        Uri baseUri = new Uri("");

        _httpClient = new HttpClient
        {
            BaseAddress = baseUri
        };

        _httpClient.DefaultRequestHeaders.ConnectionClose = false;
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        ServicePointManager.FindServicePoint(baseUri).ConnectionLeaseTimeout = 60 * 1000;
    }
}

Autofac configuration:

builder.RegisterType<MessagingService>()
            .WithParameter("httpClient", WebApiApplication._httpClient)
            .As<IMessagingService>()
            .InstancePerRequest();

Is it possible to pass the httpclient created in Global.asax.cs to the class library via Autofac? Any recommendations?

N.B. For now I can't migrate to ASP.NET core.


Solution

  • If during registration in Autofac _httpClient is null then for me it looks like registration is made before execution of Application_Start. Application_Start creates new reference, but Autofac stores old reference (null). You should reorganize your code.