ASP.NET Core MVC application dependency injection issue RRS feed

  • Question

  • Hi all,

    Recently i have tried to create a MVC application using ASP.NET Core 2.0 and i had some values defined in appsettings.json,

    "MySettings": {
        "WebApiBaseUrl": "http://localhost:6846/api/"

    In order to read these values i have added 


    above line in ConfigureServices method in Startup.cs

    and in my controller i have added

    private readonly IOptions<MySettingsModel> appSettings;
    public HomeController(IOptions<MySettingsModel> app)
         appSettings = app;

    MySettingsModel class is just a model with property same as key define in appsettings.json.
    by this method i'm able to read the value of this key.

    Now my issue is that i want to use this key in many controllers so i don't want to repeat this code in every controller so what i did was i created a BaseConntroller, added its constructor and i got my values there. But when i inherit other controllers with my BaseController , it throws me an error and tells me to generate it's constructor, so basically it tells me to add constructor in every controller which is what i wanted to avoid.

    How can i achieve this?  

    This is the error that i get


    And these are the potential fixes that it shows me

    • Moved by CoolDadTx Tuesday, July 3, 2018 1:42 PM ASP.NET related
    Tuesday, July 3, 2018 8:13 AM

All replies

  • When there is constructor with parameter inherited class musts call base constructor with it. So constructor dependency injection cannot be applied here. I thought there could be property injection to pass configuration into property. But standard .NET Core container doesn't support it. 
    Tuesday, July 3, 2018 9:31 AM
  • MVC and Core can be discussed at the ASP.NET forums.


    The basecontroller has its constructor and any controller that inherits from the basecontroller has its own constructor.

    Maybe, you should consider using a Helper class. The Helper class cannot be static and static classes shouldn't be used in ASP.NET MVC solutions from what I understand. 

    Tuesday, July 3, 2018 12:36 PM
  • Please post questions related to web development in the ASP.NET forums.

    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, July 3, 2018 1:42 PM