accessing httpclient service from within another service in .net 5

I am adding a httpclient as a service (within ConfigureServices(IServiceCollection services)) as follows:

 services.AddHttpClient<RequestsClient>(c =>
            {
                c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory");
            })
            .ConfigurePrimaryHttpMessageHandler(() =>
            {
                return new HttpClientHandler()
                {
                    UseDefaultCredentials = true
                };
            });

the RequestsClient class is constructed as:

public RequestsClient (HttpClient client, IHttpContextAccessor hca, ILogger<RequestsClient > log, Configuration config)

to use the RequestsClient service in any class/component needing it i'm injecting it as:

[Inject]
protected RequestsClient requestsClient { get; set; }

all this works great.

I'm now in need of creating a second service, lets call it "TimedService". How can I use my RequestsClient service from within my second service, TimedService?

injecting it like i do with components won't work as the RequestsClient always is null. is there a way to give TimedService service access to my RequestsClient service?

I'm sorry if this is a stupid question, I'm fairly new to this

1 answer

  • answered 2021-01-19 10:53 Zsolt Bendes

    You need to use constructor injection in TimedService.

    public class TimedService
    {
        private RequestsClient _requestClient;
        
        public TimedService(RequestsClient client)
        {
             _requestClient = client;
        }
    }
    

    I would recommend to go into typed client version. It is a bit more clearer in separation of code wise. See the official docs how to do this.