C# ASP.Net 5 配置和向后兼容类库

标签 c# asp.net

我有多个遗留库,它们通过 ConfigurationManager 进行 self 配置。示例:

var port = ConfigurationManager.AppSettings["service.port"];

新的 ASP.Net 系统更喜欢基于附加“config.json”文件的强类型模型。示例(取自 Rick Strahl's Web Log ):

//from AppSettings.cs
public class AppSettings
{
    public string SiteTitle { get; set; }
}

//from config.json
{
    "AppSettings": {
        "SiteTitle": "WebApplication2",
    },
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=blahfoo;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
    }
}

// from Startup.cs
public class Startup
{
    public IConfiguration Configuration { get; set; }

    public Startup(IHostingEnvironment env)
    {
        // Setup configuration sources.
        var configuration = new Configuration()
            .AddJsonFile("config.json")
            .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);

        configuration.AddEnvironmentVariables();
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Add Application settings to the services container.
        services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));

        …
    }
}

我的问题:有没有一种方法可以接受新的 ASP.Net 5 及其强类型配置方法,同时保持与我的其他应用程序库的向后兼容性?

或者更确切地说,我可以利用我们产品组合中的通用库而无需重写它们吗?

最佳答案

您的问题是您依赖于配置的具体实现,并使用类中的 ConfigurationManager 静态成员,而不是使用适当的依赖注入(inject)编写 SOLID 实现。

您可能会发现一些无需更改代码即可使用新配置模型的 hacky 技巧,但我认为您应该帮自己一个忙,并以此为契机实际重构您的代码并将您当前的配置抽象为一个简单的界面,例如:

公共(public)接口(interface) IMyAppConfiguration { 字符串设置 1 { 获取; } 字符串设置 2 { 得到; } SomeOtherMoreComplexSetting Setting3 { get; } }

然后在每个需要其中一项设置的类中注入(inject)此依赖项,并提供一个包装当前 ConfigurationManager 类的实现和另一个包装新配置模型的实现。

这是一个完美的例子,说明为什么 SOLID 设计很重要,如果做得好,代码维护和创新会更容易。

关于C# ASP.Net 5 配置和向后兼容类库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32634279/

相关文章:

javascript - 删除包裹在 <option> 标签周围的 <span> 标签

asp.net - 与 aspnet_regiis -ga <用户名> 相反

c# - RadComboBox 选中的值为空

c# - 如何在C#中删除某个子字符串

c# - 如何在C#中设置组合框的选定值

c# - 异步方法和等待

c# - 根据另一个列表中的值拆分自定义列表

.net - ASP.NET - 上传大文件时如何显示错误页面(超过最大请求长度)?

c# - ASP.NET GridView 'Page Not Found' 回发

c# - Status Entities in .NET Core Entity Framework - 建议的实现