codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Options Pattern in .NET Core

Changhui Xu
codeburst
Published in
4 min readNov 7, 2019

--

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 a variety of topics about the configurations in ASP.NET Core, such as named options, reloadable configuration, configuring options using DI, OptionsBuilder API, options validation, and so on.

The options pattern allows our application to follow two important software engineering principles: the Interface Segregation Principle (ISP) and Separation of Concerns. We use named options to decouple different configuration settings, so that services (classes) only depend on the specific configuration settings that they use.

In this blog post, I will not repeat the same things in the Microsoft Docs article. Instead, I will focus on the use case of the Options Pattern in DI.

Let’s write some code

We are going to build a service class MyService, which depends on some settings based on the hosting environment or some other variables. The settings could have one or more properties…

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Changhui Xu

Lead Application Developer. MBA. I write blogs about .NET, Angular, JavaScript/TypeScript, Docker, AWS, DDD, and many others.

No responses yet

Write a response