0
votes

I my .net core MVC application, when I read appsettings.json from the HomeController it works but in other classes, the AppSettings objects is never initialized.

Can anyone find out whats wrong?

I've created my custom class AppSettings where property name are mapped to the section in appsettings.json.

I've included this in the Startup.cs.

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

It works in the HomeController:

 private static AppSettings AppSettings { get; set; }

    public HomeController(IOptions<AppSettings> settings)
    {
        AppSettings = settings.Value;
    }

    private void TestMethod()
    {
        // This works inside the HomeController
        var dbString = AppSettings.DataBaseConnectionString;
    }

This constructor in BusinessLogic class will however never been called:

private static AppSettings AppSettings { get; set; }

    public BusinessLogic(IOptions<AppSettings> settings)
    {
        AppSettings = settings.Value;
    }
    private void TestMethod()
    {
        // This does NOT work inside the BusinessLogic class. Appsettings is null.
        var dbString = AppSettings.DataBaseConnectionString;
    }
1
is your "BusinessLogic" class and "HomeController" are in the same project ? - Waleed Naveed
Yes, they are in the same project. - Martin Nilsson
You are injecting the settings object into the constructor. For this to work, you should register the BusinessLogic class as a service in your IoC Container. Is that the case? Where is this BusinessLogic class used? - Sigge
The BLogic class is called directly from HomeC, everything lives in the same MVC project. HomeController.cs is in folder Controllers, as it is in a standard MVC project. BusinessLogic.cs is in another folder called Logic and this class is only called upon from other parts in this solution. Why does the same code work in HomeC but not i BLogic? I'm doing it the exact same way and does not register HomeC in any special way. I can't really answer you on the IoC Container, that term is new to me. - Martin Nilsson
services.AddOptions(); Did you add it? - go..

1 Answers

0
votes

You can register your class to DI system in Startup.ConfigureServices:

services.AddTransient<BusinessLogic>();

Then you can inject the class in anywhere , for example in controller :

private readonly BusinessLogic _businessLogic ;

public HomeController(BusinessLogic businessLogic) {
    _businessLogic = businessLogic;
}

You can read about the different lifetime and registration options :

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection