Member-only story
Options Pattern in .NET Core

When registering dependencies in the ConfigureServices
method, you must have seen a pattern like the following code snippet.
services.AddDbContext<T>(options => options.UseSqlServer(**))services.AddSwaggerGen(c => {
c.SwaggerDoc(**);
})
This pattern is essentially an extension method on top of IServiceCollection
, and the naming convention of this type of extension method is AddSomeService
. The prototype of this method is like AddSomeService(this IServiceCollection services, Action<SomeOptions> action)
. The parameter action
is a Lambda function, which can be used to provide extra configurations to the service.
In this blog post, we will create a similar service, MyService
, that can be registered to the Dependency Injection (DI) container by calling the services.AddMyService(Action<MyServiceOptions> action)
method. We will pass options to MyService
so that this service can be more flexible with extra parameters at runtime. We will also take a look at the unit testing for MyService
with its options.
The complete solution is located at this GitHub repository.
A must-read tutorial about the Options Pattern
Microsoft Docs has a detailed article about the Options Pattern in ASP.NET Core (link). This article covers…