How to access environment variable at data access layer in .NET Core

Viewed 125

My project is based on .NET Core WEB API and it has 3 layers within it i.e. The controllers, Business layer & Data layer.

I have introduced paging in WEB API so that data can be retrieved in batches. The page size is the one I'm looking forward to keep it configurable in one of configuration file.

I'm carrying my paging operation at data access layer and want to read that environment variable.

Is it good practice to do so and in what way I can achieve it ?

Any help or pointers are welcomed.

1 Answers

The preferred way to do this is via the .NET Core configuration. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0

You can have the default values set in your configuration file but they can also be overridden by environment variables.

You can also bind the configuration sections to a POCO as described here. https://medium.com/@dozieogbo/a-better-way-to-inject-appsettings-in-asp-net-core-96be36ffa22b

This will give you a strongly typed configuration object which is easier to work with.

Related