Proper way to build/Instantiate a Static Class in AspNetCore

Viewed 7083

I've built this working example of a Static AppSettings class in ASPNetCore 2017. I want to know if there is an easier/better approach to do it. I'm new so I would love some expert advice..

I'm using a MiddleWare component to instantiate my Static AppSettings class that contains all the Json appSettings values. I did this because I don't want the Controller class to have to know about setting the Connection string of the DB in which it wants to query. And i'm using SQLClient (not EF, because all my calls are to Stored Procedures).

Here is my code:

appSettings.Json

{ "AppSettings": { "WarehouseConnectionString": "Data Source=[Removed]\SQLExpress;Initial Catalog=Warehouse;Integrated Security=True;" }, }

AppSettings Class

public class AppSettings
{       
    public AppSettings()
    {
        // Set default values of our options.
        WarehouseConnectionString = "WarehouseConnectionString";
    }

    /// <summary>
    ///  Our Warehouse DB Connection string.
    /// </summary>
    public static string WarehouseConnectionString { get; set; }
}

My MiddleWare class:

public class ApplicationSettingsService
{
    private readonly RequestDelegate next;

    public ApplicationSettingsService(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context, IOptions<AppSettings> appSettings)
    {            
            // Create our static instance of our AppSettings class.                
            AppSettings _settings = appSettings.Value;

            await next(context);            
    }
}

My Starup.cs class

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //************************************************//
        // Adds services required for using options.
        //************************************************//
        services.AddOptions();

        //**********************************************************************//
        // Register the IConfiguration instance which MyOptions binds against the 
        // AppSettings section of the appsetting.json file only.
        //**********************************************************************//
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));         

        // Add framework services.
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        //******************************************************//
        // Add our own custom Application Settings Middleware     //
        //******************************************************//             
        app.UseMiddleware<ApplicationSettingsService>();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                //template: "{controller=Home}/{action=Index}/{id?}");
                template: "{controller=Box}/{action=Index}/{id?}");
        });
    }
}

My Database Connection Class that uses the AppSetting Values.

public static class DBConnection
{
    private static string ConnectionString = AppSettings.WarehouseConnectionString;


    public static SqlConnection GetConnection()
    {
        return new SqlConnection(ConnectionString);
    }
}

When the client (Controller) makes a call to the DB Class, they do not have to specify the Connection string, the "Warehouse" already knows what DB it should connect to...

   DHRIM5_StoredProcedureDatabaseExample.Data.Warehouse.StoredProcedures sp = new Data.Warehouse.StoredProcedures();

    // GET: Box
    public ActionResult Index()
    {            
        IList<Box> tests = sp.SPGetBoxes().ToList();            
        return View(tests);
    }

Thanks for your help.

1 Answers
Related