Living. Dreaming. Coding
Injecting config settings in .NET Core MVC Views

Injecting config settings in .NET Core MVC Views

After playing around with MVC on .net core a little i realized I needed to have some maps functionality using static bing maps on my site. So after getting a key and reading through some documentation I found out that i needed to set the license key in the map url like this: “,400&key=[YOUR_KEY_HERE]”.

I knew that I could use the dependency injection available to inject the configuration and key in all my models however this seemed cumbersome and a lot of work for something so simple. I knew there had to be a better way for this.After looking around I discovered a really nice and clean solution for my problem which I’ll explain down here.

The first thing we need is a settings class:


This is our storage class for our Appsettings which in this example will have one value.

public interface IAppSettings
    string MapsKey { get; set; }
public class AppSettings : IAppSettings
    public string MapsKey { get; set; }

    public AppSettings(string mapsKey)
        MapsKey = mapsKey;

After finishing that I needed to wire up the Dependency Injection so that it will provide me with an instance when I need it. To do that add the following to startup.cs


services.AddSingleton<IAppSettings>(new AppSettings(Configuration["BingMaps:Key"]));

This registers the dependency as a singleton and passes the settings from the appsettings.json to this class. But now I needed a way to get it injected into the razor page.


To allow the settings to be injected in the view you need to add the @inject to its razor page as you can see below:

@using MyProject.Settings
@inject IAppSettings AppSettings;

After you finished this you can then use this like any normal razor variable and append the key to the url like this:

<img src=",400&[email protected]"/>


Leave a Reply

Your email address will not be published.