Search code examples
asp.netdependency-injectionconfigurationblazor-server-side

How do I inject IConfiguration to a class using a constructor?


The official documentation for Asp.net core (linked at the bottom) shows that I should inject the configuration into my class like this:

public partial class IndexBase : ComponentBase
{
    private readonly IConfiguration Configuration;

    public IndexBase(IConfiguration configuration)
    {
        Configuration = configuration;
    }
}

However this results in the error CS7036: There is no argument given that corresponds to the required parameter 'configuration' of 'IndexBase.IndexBase(IConfiguration)'

I've found that I can successfully inject the configuration using this method:

public partial class IndexBase : ComponentBase
{
    [Inject] IConfiguration _configuration { get; set; }
}

But the problem with this method is that it doesn't work inside the class constructor, only other methods. I need to be able to use configuration info inside the constructor to set up other fields.

Also, adding builder.Services.AddSingleton<IConfiguration>(); to program.cs doesn't change anything. Other than that, I have not modified program.cs at all.

Can anyone see a reason why this might not be working?

Sources:


Solution

  • You're confused.

    IndexBase isn't a DI service, it's a component. Instances are "constructed" by the Renderer, not within the Services container.

    This will error because the Renderer has no idea how to provide IConfiguration.

    public partial class IndexBase : ComponentBase
    {
        private readonly IConfiguration Configuration;
    
        public IndexBase(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    }
    

    This works because the Renderer reads all the Inject attributes from a component, gets them from the service container and assigns them though reflection. This happens after the constructor is run, but before the first call to SetParametersAsync.

    public partial class IndexBase : ComponentBase
    {
        [Inject] IConfiguration _configuration { get; set; }
    }
    

    I need to be able to use configuration info inside the constructor to set up other fields.

    Not possible in a component. Rethink your logic.

    This doesn't work either:

        public IndexBase(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    

    You need to make a call to base within the constructor.

        public IndexBase(IConfiguration configuration): base()
        {
            Configuration = configuration;
        }
    

    Whatever you want to do, do it in OnInitialized. It all happens once, and before the component renders.

    If you still think you need to run some code in the constructor, explain what in your question, and why you can't do it later in the process.