.NET Dependency Injection's ServiceCollection Extension Methods

It is important when registering services to do the right thing. There’s six helper methods that will see typical use:

  • TryAddSingleton
  • TryAddScoped
  • TryAddTransient
  • AddSingleton
  • AddScoped
  • AddTransient

Is there only to be one implementation? Then you want a TryAdd* method. Most of the time, you’re only going to need a single implementation, but when you want a collection of services implementing the same interface, the Add* methods are there for you.

Now you need to choose between the available lifetimes:

  • Singleton - a single instance will exist for the lifetime of the app. This doesn’t mean that it initializes on registration, but that resolver will only generate one instance.
  • Scoped - an instance will be reused for the life of the scope - typically this will be the life of an HttpRequest.
  • Transient - every time the resolver will create a new instance. This is the simplest to implement due to the lack of state, but be careful.

.NET 8 adds keyed services, and there’s also some other useful utilities for quickly instantiating services at startup.

References:

.NET Framework + Microsoft.Extensions.DependencyInjection

Say you’re a developer, and you’re stuck with a Frankenstein’s monster of a .NET Framework web application. No big deal, but you want to modernize a piece of it. You’re almost certainly want to involve Microsoft.Extensions.DependencyInjection, the marvelous standard (modern) .NET Dependency Injection (DI) library. There’s good news: it targets .NET Standard 2.0, which means it is backwards compatible with .NET Framework. The bad news? You’re stuck manually wiring it up, because ASP.NET MVC 5 doesn’t do all the magic work that ASP.NET Core does for you.

Continue reading...

Hi Again!

Let’s try this again shall we? I’m currently working on an FSharp library to facilitate running/playing a The One Ring 2e campaign. I hope to talk about some of the lessons learned around Test Driven Development and Functional Programming with Types.

Continue reading...

Bluebonnets!

Taking pictures of my daughter in bluebonnets, and she picks one and shoves it down her shirt. Priceless.

Continue reading...

Yet another blog format change

View Archive (44 posts)