I may be barking up the wrong tree here, but, i have the following:
var host = new HostBuilder()
.ConfigureServices(services =>
{
services.AddSingleton<IHttpClientFactory>();
services.AddScoped<IPaintMapper, PaintMapper(XXXXX, config)>();
};
I want to pass the IHttpClientFactory into my Scoped "PaintMapper", which i will provide also a config for.
How would i do this? As the IHttpClientFactory and the "config" are both required to setup the scoped instance.
I've been at this refactor for a while and think my brain is not handling it particularly well, so my apologies if i'm missing something normal - but i don't see this done elsewhere, so i'm probably missing something.
CodePudding user response:
You can do like this
services.AddScoped<IPaintMapper, PaintMapper>(provider => {
var config = provider.GetRequiredService<Config>();
var httpFactory = provider.GetRequiredService<IHttpClientFactory>();
// Do stuff with mapper
return mapper;
});
CodePudding user response:
The usual approach is to just register IHttpClientFactory
and config type and resolve them from ctor. Scoped services can resolve singleton ones:
services.AddHttpClient(); // install Microsoft.Extensions.Http nuget
services.AddXXX<PaintMapperSettings>();
services.AddScoped<IPaintMapper, PaintMapper>();
class PaintMapperSettings
{
}
class PaintMapper
{
public PaintMapper(IHttpClientFactory factory, PaintMapperSettings settings)
{
}
}
For options to register and resolve settings - see the docs. Personally I tend to use the options pattern.