【问题标题】:Proper way to build/Instantiate a Static Class in AspNetCore在 AspNetCore 中构建/实例化静态类的正确方法
【发布时间】:2017-07-12 13:06:21
【问题描述】:

我已经在 ASPNetCore 2017 中构建了这个静态 AppSettings 类的工作示例。我想知道是否有更简单/更好的方法来做到这一点。我是新人,所以我希望得到一些专家的建议..

我正在使用 MiddleWare 组件来实例化包含所有 Json appSettings 值的静态 AppSettings 类。我这样做是因为我不希望 Controller 类必须知道设置它想要查询的 DB 的 Connection 字符串。而且我正在使用 SQLClient(不是 EF,因为我所有的调用都是对存储过程的调用)。

这是我的代码:

appSettings.Json

{ “应用程序设置”:{ “WarehouseConnectionString”:“数据源=[已删除]\SQLExpress;初始目录=仓库;集成安全=True;” }, }

AppSettings 类

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; }
}

我的中间件类:

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);            
    }
}

我的 Starup.cs 类

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?}");
        });
    }
}

使用 AppSetting 值的我的数据库连接类。

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


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

当客户端(控制器)调用数据库类时,他们不必指定连接字符串,“仓库”已经知道它应该连接到哪个数据库...

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

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

感谢您的帮助。

【问题讨论】:

标签: c# json asp.net-mvc asp.net-core


【解决方案1】:

一般来说,您应该避免使用依赖于基础架构的静态类,因为很难对此类类进行单元测试。但是您可以在单例范围内使用非静态类,因此您将只有一个实例。在你的情况下 - AppSettings.cs

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

    public string WarehouseConnectionString { get; set; }
}

在Startup.cs 中从Configuration 获取值并将其注册为单例。

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    var appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
    services.AddSingleton(appSettings);
}

然后你可以把这个值注入到构造函数中

public class DBConnection
{
    private readonly string connectionString;

    public DBConnection(AppSettings settings)
    {
        this.connectionString = settings.WarehouseConnectionString;
    }

    public SqlConnection GetConnection()
    {
        return new SqlConnection(this.connectionString);
    }
}

请注意,在这种情况下AppSettings 在启动应用程序时是只读的,因此如果您更改appsettings.json 文件,则在不重新启动应用程序的情况下将不会应用设置。
现在您还应该将DbConnection 注册为Startup.cs - services.AddSingleton&lt;DBConnection&gt;(); 中的单例,并通过构造函数参数请求其对象。

public class StoredProcedures
{
    private readonly DBConnection connection;
    public StoredProcedures(DBConnection connection)
    {
        this.connection = connection;
    }
}

当然最好将接口与实现分开,只使用接口。

【讨论】:

  • 从哪里以及如何调用 DBConnection?
猜你喜欢
  • 1970-01-01
  • 2023-04-03
  • 2011-06-07
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
相关资源
最近更新 更多