【发布时间】: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);
}
感谢您的帮助。
【问题讨论】:
-
静态类无法实例化。
-
您也可以在 EF 中使用 SP:entityframeworktutorial.net/…
-
查看
IOptions<T>和 docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration 上的文档,了解如何在 ASP.NET Core 中使用选项/配置
标签: c# json asp.net-mvc asp.net-core