Extracting Service Configuration in Dotnet 5

Taylor Goodall
2 min readDec 9, 2020

A trusted pattern for keeping your config seperated and clean

Photo by Timothy Dykes on Unsplash

This blog posts is a simple guide on how we can extract services from our startup.cs file separate configuration files allowing us to have dedicated configuration and keep our main startup.cs file as minimal as possible.

by default in ASP.net core 5 we get Swagger out of the box, let’s start with extracting this out to to its own configuration file

We can extract out the above code to a SwaggerConfig.cs file which will contain all of our swagger specific configuration as required. I have created a Configurations folder in the root of my project

We can then go ahead and Register this to our services in startup.cs Don’t forget to import the namespace of your configuration as well.

we can also extract Swagger Configuration shown below

This can be done by adding the below method to our SwaggerConfig file

then update the ConfigureServices method to be

We can also use this pattern to bootstrap our own services and keep our startup as minimal as possible, You can break your services out as needed, for example you may want all of your repositories in a separate configuration file

Update startup.cs as follows

Conclusion

Splitting our service configuration into separate files is an extremely useful pattern to use within your codebase and can make maintenance of your project a lot easier when it comes to knowing where to look for changes. It may not be worth it when setting up a fresh project, however if you notice your startup.cs start to become muddied I would recommend reaching for this pattern.

Questions? Say hello on twitter

originally published on taylorgoodall.me on 08/12/2020

--

--

Taylor Goodall
0 Followers

Software Engineer living in Adelaide, interested in full stack development, ops & infosec