Whilst doom scrolling Twitter last night, I came across a tweet by a Norweigan software developer named KarlSolgard; he tweeted about a feature of .NET Core Dependency Injection that I was unaware existed.

Injecting a class or a factory is something that every .NET developer has come to know; however, you can inject an IEnumerable of something. By registering multiple implementations of an interface, your classes can ask for an array of concrete implementations of that interface.

var services = new ServiceCollection()
.AddSingleton<IMessageHandler, EmailHandler>()
.AddSingleton<IMessageHandler, SmsHandler>()
.AddSingleton<IDataSource, FakeDataSource>()
.AddSingleton<IMessageSender, MessageSender>()
.BuildServiceProvider();

var dataSource = services.GetService<IDataSource>();
var messages = await dataSource!.GetPendingMessagesAsync();
var sender = services.GetService<IMessageSender>();

await sender!.SendMessagesAsync(messages);

I asked the tweet’s author for an example, and they replied with a way to tackle the traditional FizzBuzz challenge, but I wasn’t satisfied and challenged myself to look for a more practical example.

Sending messages to different services based on some internal logic is often a pattern I have to write. So I went away and wrote a basic message sending system that doesn’t contain any hardcoded logic to determine how to send different messages.

The code in my demo repository isn’t a complete example, and it may be a bit contrived, but it does show a practical implementation of the ‘IEnumerable Injection’ pattern.

Cover Photo by @ivvndiaz on Unsplash