0

I am in the process of migrating a large solution from .NET Framework 4.8 to .NET 9.0. I used .NET Upgrade Assistant to get started. I have a long way to go.

All of the projects in the solution have their own static DataAccess class using System.Data.SqlClient for all database interaction. (That's a problem I'll deal with next.)

How do I get the connection string from appsettings.json into a static class, where I can't call a constructor?

namespace MyProject
{
    public static class DataAccess
    {
        /* LEGACY:
        private static string m_ConnectionString =
            ConfigurationManager.ConnectionStrings["DefaultConnStrg"].ConnectionString;
        */
        private static string m_ConnectionString = string.Empty;
        private static IConfiguration m_Config;

        // This will not compile! "CS0710: Static classes cannot have instance constructors."
        public ShopDataAccess( IConfiguration configuration )
        {
            m_Config = configuration;
            m_ConnectionString = m_Config.GetConnectionString( "DefaultConnStrg" );
        }
    ...
}

2 Answers 2

1

My guess is that a lot of problems will be resolved once you move away from the static DataAccess class. It seems that your legacy app spun its own Factory-like scheme that can be handled cleanly using native .NET & EntityFrameworkCore.

DbContext instances (or DbContextFactory instances) can be set up to be available from the IServiceProvider, or injected directly into controllers or other service classes. DbContexts or DbContextFactories will get their connection strings within the static Main method, where you build your IConfiguration to go into the IServiceProvider and can pull connections strings at the same time.

Is each DataAccess the same DbContext or are there different tables, etc., involved? If they are the same, create a projects for your DAL from which each of your other projects can depend.

Sign up to request clarification or add additional context in comments.

3 Comments

The various projects have some overlap (users, orders, etc.), but each project has it's own data interactions also (ecommerce, B2B partners, etc.). We keep the stored procedures and data access code unique to each project in that project. We have a common library that all projects reference where common data access lives. This is a 20 year old code base, migrated through many platforms over the years. We don't have the resources for a full redesign.
There are a few other static classes in the solution, helpers, utilities, etc. They will need access to config values as well. So the question remains.
If you need config values in helper/extension methods, perhaps you need to refactor those as well to accept them, or an IConfiguration, or an IOptions<POCO>, as parameters. The resulting architecture will be much less fragile (and perhaps more testable).
1

How do I get the connection string from appsettings.json into a static class, where I can't call a constructor?

You need to initialize the configuration when the app starts. Refer to the following sample:

In the appsettings.json file, there have a connection string:

{
  "ConnectionStrings": {
    "DefaultConnection": "......"
  },

Create a static class AppSettings.cs:

public static class AppSettings
{
    public static string? ConnectionString { get; private set; }

    public static void Initialize(IConfiguration configuration)
    {
        ConnectionString = configuration.GetConnectionString("DefaultConnection");
    }
    public static string GetConnectionString()
    {
        return ConnectionString;
    }
}

Then, initialize the AppSettings in the Program.cs:

    var builder = WebApplication.CreateBuilder(args);
    ...
    // Initialize AppSettings
    AppSettings.Initialize(builder.Configuration);

    var app = builder.Build();
    ...

After that you can access connection string use the following code:

    public IActionResult Index()
    {
        var connection = AppSettings.ConnectionString;
        var connection2 = AppSettings.GetConnectionString();
        return View();
    }

The result as below:

result

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.