https://github.com/dotnet-labs/optionspattern
Options Pattern in .NET Core
https://github.com/dotnet-labs/optionspattern
dependency-injection design-patterns dotnet dotnetcore options options-pattern
Last synced: 4 months ago
JSON representation
Options Pattern in .NET Core
- Host: GitHub
- URL: https://github.com/dotnet-labs/optionspattern
- Owner: dotnet-labs
- License: mit
- Created: 2020-07-09T03:14:59.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2023-12-07T23:07:18.000Z (about 2 years ago)
- Last Synced: 2025-04-11T01:39:49.325Z (10 months ago)
- Topics: dependency-injection, design-patterns, dotnet, dotnetcore, options, options-pattern
- Language: C#
- Homepage:
- Size: 13.7 KB
- Stars: 9
- Watchers: 4
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE.md
Awesome Lists containing this project
README
# Options Pattern in .NET Core
This solution demos one of the usages of the Options Pattern in .NET Core.
## [Medium Article: Options Patter in .NET Core](https://codeburst.io/options-pattern-in-net-core-a50285aeb18d)
When registering dependencies in the `ConfigureServices` method, you must have seen a pattern likes the following
```CSharp
services.AddDbContext(options => options.**)
services.AddSwaggerGen(c => {
c.SwaggerDoc(**);
})
```
This pattern is actually an extension method on top of `IServiceCollection`, and the naming convention of this type of extension method is `AddSomeService(this IServiceCollection services, Action action)`. The `action` is a Lambda function, which can be used to provide extra parameters to the service.
In this blog post, we will create a similar service that can be registered by calling the `services.AddMyService(Action action)` method. We will pass options to `MyService` so that this service can be more flexible with extra parameters.
## Intro to Options pattern in ASP.NET Core
[Microsoft Doc](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options)
The options pattern uses classes to represent groups of related settings. When configuration settings are isolated by scenario into separate classes, the app adheres to two important software engineering principles:
- The Interface Segregation Principle (ISP) or Encapsulation – Scenarios (classes) that depend on configuration settings depend only on the configuration settings that they use.
- Separation of Concerns – Settings for different parts of the app aren't dependent or coupled to one another.
## How to Create an Option Object in Tests
```csharp
Options.Create(new MyServiceOptions
{
Option1 = "say hello",
Option2 = true
}
)
```
## License
Feel free to use the code in this repository as it is under MIT license.