Skip to content

Instantly share code, notes, and snippets.

@nycdotnet
Last active February 6, 2024 20:00
Show Gist options
  • Save nycdotnet/d1cc7a0c9f042f58d9fb57fce3a1aea4 to your computer and use it in GitHub Desktop.
Save nycdotnet/d1cc7a0c9f042f58d9fb57fce3a1aea4 to your computer and use it in GitHub Desktop.

Pattern Matching

List and similar:

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
            }
        }
    }  

Microsoft Dependency Injection

Registering a named HTTP client using config:

  // 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");
  });

Using an HTTP client registered by name:

Use constructor injection or some other technique to resolve an IHttpClientFactory. Then resolve the named client like this:

  var client = httpClientFactory.CreateClient("MyNamedHttpClient");

General-purpose DI container (for console app, or tests, etc)

  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>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment