Custom IOptions service

Create a new console application and add packages for DI and Hosting:

dotnet new console
dotnet add package Microsoft.Extensions.Hosting
dotnet add package Microsoft.Extensions.DependencyInjection

Add a class for the new object, and an extension method for registering it with dependency injection:

class Foo
	public string Name { get; set; } = "Not set";

static class FooExtensions
	public static IServiceCollection AddFoo(
		this IServiceCollection services, Action<Foo>? options = null)
		return services.Configure(options ?? (x => { }));

Build your hosted service:

partial class Program : BackgroundService
	private readonly Foo _foo;

	public Program(IOptions<Foo> foo)
		_foo = foo.Value;

	protected override Task ExecuteAsync(CancellationToken stoppingToken)
		return Task.CompletedTask;

Build your application entry point, and you can use the options pattern to configure your custom object while registering it:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

await Host.CreateDefaultBuilder(args)
	.ConfigureServices((HostExecutionContext, services) =>
		// services.AddFoo();
		// OR
		services.AddFoo(options =>
			options.Name = "Hello";


IOptions is a singleton, so the Foo object will only be generated once.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s