We use StructureMap in some old project and we an trying to migrate to .NET 6 using the default dependency injection. This is a StructureMap piece that we want to migrate across.
container.Configure(config =>
{
config.For<IBookingApiClient>().Use(new BookingApiClient(
new CorrelationHttpClient(
container.GetInstance<HttpClient>("BookingApi"),
container.GetInstance<ICorrelationIdReader>())
)).Transient();
});
This is what we currently have in the ASP.NET Core 6 Web API, but we can't figure out how we might get the HttpClient
and ICorrelationIdReader
as we have not build the service yet, as we are still constructing it?
builder.Services.AddHttpClient("BookingApi", client =>
{
client.BaseAddress = new Uri(settingsReader.GetRequiredSettingValue("BookingApiClientUrl"));
});
builder.Services.AddTransient<IBookingApiClient>(
new BookingApiClient(
new CorrelationHttpClient(?,?)));
There are several overloads of Add{Lifetime}
methods which accept implementation factory Func<IServiceProvider, TService>
, so you can use them to mimic the behaviour. Something along these lines:
builder.Services.AddTransient<IBookingApiClient>(sp =>
{
var httpClientFactory = sp.GetRequiredService<IHttpClientFactory>();
var httpClient = httpClientFactory.CreateClient("BookingApi");
return new BookingApiClient(
new CorrelationHttpClient(httpClient, sp.GetRequiredService<ICorrelationIdReader>()));
});
Note that while you can do this, I would argue that more idiomatic approach would be to register CorrelationHttpClient
as a typed client and just use builder.Services.AddTransient<IBookingApiClient, BookingApiClient>()
registration.