This is null safe for Items
in this example. 40x Faster than using ?.Any()
in a microbenchmark when Items is not null but could be empty. In cases where the list will typically be null, ?.Any()
measured about 10x faster, but these are all sub-nanosecond measurements and neither has any allocations.
public class Foo
{
public List<int>? Items { get; set; }
public void ProcessItems()
{
if (Items is { Count: > 0 })
{
// do stuff
}
}
}
// or another kind of builder ...
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient("MyNamedHttpClient", static (services, httpClient) => {
// this method is run when the client is resolved.
// resolves the config from the services collection
var config = services.GetService<IConfiguration>();
// configures the client
httpClient.BaseAddress = new Uri(config.GetValue<string>("MyNamedHttpClientBaseAddress"));
httpClient.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/json");
});
Use constructor injection or some other technique to resolve an IHttpClientFactory
. Then resolve the named client like this:
var client = httpClientFactory.CreateClient("MyNamedHttpClient");
var containerBuilder = Host.CreateApplicationBuilder();
// register a singleton to represent a specific interface. (the interface is optional)
containerBuilder.Services.AddSingleton<WhateverInterface>(new WhateverClass());
containerBuilder.Services.AddTransient<WhateverClass>();
containerBuilder.Services.AddSingleton(x => { /* x is an IServiceProvider and has .GetRequiredService etc */ });
var container = containerBuilder.Build();
var myThing = container.Services.GetRequiredService<WhateverClass>();