Check app configuration in a EF migration class

Angela_HAC 20 Reputation points
2025-02-25T09:49:07.9966667+00:00

Hello,

I have an web api hosted in Azure that connect to an SQL Database. Any changes to the database schema are done through EF Core Migrations.

In a migration class (Microsoft.EntityFrameworkCore.Migrations.Migration) I would like to access the IConfiguration. I tried to inject it but it fails since this type of classes require parameterless ctor.

I would need this because I am using versioned tables and I need to set HISTORY_RETENTION_PERIOD with values read from app settings.

Angela

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,317 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hongrui Yu-MSFT 4,605 Reputation points Microsoft Vendor
    2025-02-26T07:35:31.55+00:00

    Hi, @Angela_HAC. Welcome to Microsoft Q&A. 

    If you cannot adjust the constructor parameters and cannot perform dependency injection, you could consider setting IConfiguration as a static property for global access.

    Create a static class

    public static class GlobalConfiguration
    {
            public static IConfiguration? Configuration { get; set; }
    }
    

    Assign value in Program or Startup

    GlobalConfiguration.Configuration = app.Services.GetService<IConfiguration>();
    

    Get IConfiguration where needed

    var _configuration = GlobalConfiguration.Configuration;
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.