Omar93
Omar93

Reputation: 45

C# IoC configuration: how can I inject an object when one of its parameters it's not an already injected object?

I'm using the Microsoft.Extensions.DependencyInjection library and I have this concrete class which implements a generic interface called IInterface

using System.Net.Http;

namespace my.namespace
{
    public class Concrete : IInterface
    {
        private readonly IHttpClientFactory _factory;
        private readonly string _s1;
        private readonly string _s2;

        public Concrete(IHttpClientFactory factory, string s1, string s2)
        {
            _factory = factory;
            _s1 = s1;
            _s2 = s2;
        }
    }
}

In my IocConfig.cs I'm injecting the IHttpClientFactory, like this:

services.AddHttpClient("clientName", client =>
            {
            });

Now I also want to inject the Concrete class. Since the s1 and s2 parameters are outside my already defined dependencies I think I should use the explicit constructor, like this:

services.AddScoped<IInterface, Concrete>(sp => new Concrete(/* parameters */));

If all the parameters required by the constructor would have been already defined dependencies I should have done it this way:

services.AddScoped<IOtherInterface, OtherConcrete>();

How can I inject this class correctly providing all the parameters needed? I think I need to explicitly pass IHttpClientFactory and also both s1 and s2 strings but I don't know how to do it.

Upvotes: 0

Views: 249

Answers (1)

lrpe
lrpe

Reputation: 799

The lambda function passed to AddScoped takes an IServiceProvider as input. You can use this to resolve an IHttpClientFactory by calling GetService<IHttpClientFactory>().

services.AddScoped<IInterface, Concrete>(sp
    => new Concrete(sp.GetService<IHttpClientFactory>(), "s1", "s2"));

Upvotes: 2

Related Questions