none
ASP.NET Core MVC application dependency injection issue

    Pertanyaan

  • 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 

    services.Configure<MySettingsModel>(Configuration.GetSection("MySettings"));

    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

    Error

    And these are the potential fixes that it shows me

    • Dipindahkan oleh CoolDadTxMVP 03 Juli 2018 13:42 ASP.NET related
    03 Juli 2018 8:13

Semua Balasan

  • 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. 
    03 Juli 2018 9:31
  • MVC and Core can be discussed at the ASP.NET forums.

    https://forums.asp.net/

    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. 

     
    03 Juli 2018 12:36
  • Please post questions related to web development in the ASP.NET forums.

    Michael Taylor http://www.michaeltaylorp3.net

    03 Juli 2018 13:42