- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
首先是问题:
这可能吗?我的灵感来自 Joe Wrobel's work (被遗忘的 Codeplex project 的还原)。在这里,您为提供者创建您的配置文件,它为它创建强类型,有效地为 Profile 类创建外观。
现在是背景故事!
我真的不喜欢magic strings .它们非常糟糕,在更新您的应用程序时可能会导致一些严重的问题。使用过 PHP 和 ColdFusion 等语言后,我知道将它们放入您的应用程序并在需要更改它们之前忘记它们很容易。然后你必须找到它们的每一个变体并相应地改变它们。
如果您遵循“开箱即用”的应用程序模板,.NET 并没有那么好。许多示例使用 web.config 中的 appsettings 来存储各种设置。这确实是一个很好的存储位置,并且非常适合大多数应用程序。然而,当您开始直接调用它们时,问题就开始出现了——例如 ConfigurationManager.AppSettings["MyAppSetting"]
。然后,当您重新使用魔术字符串时,您的生活实际上并不比 PHP 用户好多少。
这是facades的地方进来。Facades 提供了一种方法,可以在一个地方从一个神奇的字符串创建一个强类型的对象,并让开发人员从应用程序的其余部分引用它。
现在,我不再使用 web.config 来包含我的应用程序设置,而是使用数据库来保存它们。在应用程序启动时,名称/值组合被检索,然后通过 Set
按顺序添加到 ConfigurationManager.AppSettings
。没什么大不了的(除了我之前的 problem!)。
我的数据层、服务层和表示层都可以访问这个“应用程序外观”,并保存诸如应用程序模式之类的东西,哪个服务端点使用 yada yada yada 并限制必须寻找许多魔术字符串的需要,向下到两个神奇的字符串 - 一个(名称)在外观中,另一个(名称和值)在创建点(对我来说是数据库)。
这个门面类最终会变得很大,我最终会厌倦必须更新它们。
所以我想做的是有一个 ApplicationFacade 类,它在每次构建完成时自动生成。现在回到起点……这可能吗?
最佳答案
您也可以为此目的使用 CodeSmith 模板。优点是您可以在模板文件属性中设置要在每次构建时重新生成(设置 BuildAction = "Complile")
已编辑我也在寻找这样的解决方案。谷歌搜索后,我找到了基本的 T4 模板来生成这样一个类。我重新设计了它,您可以在下面找到它。
模板正在从您的 Web.config/App.config 文件中为 appSetting 部分生成包装器类
假设您在配置文件中有以下几行设置
<appSettings>
<add key="PageSize" value="20" />
<add key="CurrentTheme" value="MyFavouriteTheme" />
<add key="IsShowSomething" value="True" />
</appSettings>
处理模板后你会得到下面的类
namespace MyProject.Core
{
/// <remarks>
/// You can create partial class with the same name in another file to add custom properties
/// </remarks>
public static partial class SiteSettings
{
/// <summary>
/// Static constructor to initialize properties
/// </summary>
static SiteSettings()
{
var settings = System.Configuration.ConfigurationManager.AppSettings;
PageSize = Convert.ToInt32( settings["PageSize"] );
CurrentTheme = ( settings["CurrentTheme"] );
IsShowSomething = Convert.ToBoolean( settings["IsShowSomething"] );
}
/// <summary>
/// PageSize configuration value
/// </summary>
public static readonly int PageSize;
/// <summary>
/// CurrentTheme configuration value
/// </summary>
public static readonly string CurrentTheme;
/// <summary>
/// IsShowSomething configuration value
/// </summary>
public static readonly bool IsShowSomething;
}
}
将以下代码保存到 *.tt 文件 并包含到您要放置生成文件的项目中。在每个构建中重新生成类 see my answer here模板从值中识别字符串、日期时间、整数和 bool 类型
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="Microsoft.VisualBasic" #>
<#@ template language="VB" debug="True" hostspecific="True" #>
<#@ output extension=".Generated.cs" #>
<#
Dim projectNamespace as String = "MyProject.Core"
Dim className as String = "SiteSettings"
Dim fileName as String = "..\..\MyProject.Web\web.config"
Init(fileName)
#>
//------------------------------------------------------------------------------
// FileName = <#= path #>
// Generated at <#= Now.ToLocaltime() #>
//
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
// NOTE: Please use the Add a Reference to System.Configuration assembly if
// you get compile errors with ConfigurationManager
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Configuration;
namespace <#= projectNamespace #>
{
/// <remarks>
/// You can create partial class with the same name in another file to add custom properties
/// </remarks>
public static partial class <#= className #>
{
/// <summary>
/// Static constructor to initialize properties
/// </summary>
static <#= className #>()
{
var settings = System.Configuration.ConfigurationManager.AppSettings;
<#= AddToCostructor(path) #> }
<#= RenderApplicationSettings(path) #> }
}
<#+
Dim path as String = ""
Dim doc as XDocument = Nothing
Public Sub Init(fileName as String)
Try
path = Host.ResolvePath(fileName)
If File.Exists(path) Then
doc = XDocument.Load(path)
End If
Catch
path = "<< App.config or Web.config not found within the project >>"
End Try
End Sub
Public Function AddToCostructor(ByVal path as String) as String
If doc Is Nothing Then Return ""
Dim sb as New StringBuilder()
For Each result as XElement in doc...<appSettings>.<add>
sb.Append(vbTab).Append(vbTab).Append(vbTab)
sb.AppendFormat("{0} = {1}( settings[""{0}""] );", result.@key, GetConverter(result.@value))
sb.AppendLine()
Next
Return sb.ToString()
End Function
Public Function RenderApplicationSettings(ByVal path as String) as String
If doc Is Nothing Then Return ""
Dim sb as New StringBuilder()
For Each result as XElement in doc...<appSettings>.<add>
dim key = result.@key
sb.Append(vbTab).Append(vbTab)
sb.Append("/// <summary>").AppendLine()
sb.Append(vbTab).Append(vbTab)
sb.AppendFormat("/// {0} configuration value", key).AppendLine()
sb.Append(vbTab).Append(vbTab)
sb.Append("/// </summary>").AppendLine()
sb.Append(vbTab).Append(vbTab)
sb.AppendFormat("public static readonly {0} {1}; ", GetPropertyType(result.@value), key)
sb.AppendLine().AppendLine()
Next
Return sb.ToString()
End Function
Public Shared Function GetConverter(ByVal prop as String) as String
If IsNumeric(prop) Then Return "Convert.ToInt32"
If IsDate(prop) Then Return "Convert.ToDateTime"
dim b as Boolean
If Boolean.TryParse(prop, b) Then Return "Convert.ToBoolean"
Return ""
End Function
Public Shared Function GetPropertyType(ByVal prop as String) as String
If IsNumeric(prop) Then Return "int"
If IsDate(prop) Then Return "DateTime"
dim b as Boolean
If Boolean.TryParse(prop, b) Then Return "bool"
Return "string"
End Function
#>
关于c# - 自动生成一个强类型的 AppSettings 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1583642/
我可以拥有吗?我的 app.config 中的部分包含许多设置,但也引用了 不同文件中的部分? 这将允许我保留只有开发人员应该感兴趣的配置选项,例如在主窗口上显示调试输出的选项(非常困惑但对我有用)或
我正在使用通过控制台应用程序创建的 app.config 文件,我可以使用 ConfigurationSettings.AppSettings["key1"].ToString()
我搜索了该站点,虽然我找到了一些非常有用的信息,但我无法弄清楚我的代码发生了什么。我有以下 web.config: 我
我正在使用 az functionapp config appsettings 自动创建我的 Azure Function 设置。我的设置之一是其中包含空格的 SQL 连接字符串。连接字符串中的空格导
我正在使用 az functionapp config appsettings 自动创建我的 Azure Function 设置。我的设置之一是其中包含空格的 SQL 连接字符串。连接字符串中的空格导
工具:VS2017、ASP.NET Core 2、Entity Framework Core 2、ASP.NET Core JavaScript 服务 我正在使用以下 BuildWebHost 方法:
我正在使用 ASP.NET Core 2.1。我在 appsettings.json 中有设置我使用选项模式将它们绑定(bind)到类。我想在 appsettings.Production.json
我在 appsettings.Development.json 上有点挣扎覆盖或以其他方式与 appsettings.json 合并.我不确定如何使用 appsettings.Development.
我真的很希望能够有一种方法来获取当前使用 ConfigurationManager.AppSettings [“mysettingkey”] 来获取其设置的应用程序,以使这些设置实际上来自中央数据库而
我有一些需要从多个文件访问的字符串常量。由于这些常量的值可能会不时更改,因此我决定将它们放在 AppSettings 而不是常量类中,这样我就不必在每次更改常量时都重新编译。 有时我需要处理单个字符串
我的 App.config 中有这样的代码片段 - 在 master_AppSettings.config 文件中,我将“ApplicationDSN”设置为“ABCConnectionStri
我有一个希望非常简单的问题。 如果我有值,我想从 Web.config 的 AppSettings 中找到某个键 为了简单起见,是否可以通过指定值而不是键来找到 AppSettings 条目
我正在使用 .NET Web API(4.6 框架)编写应用 我有一个我使用的属性:[ApiExplorerSettings(IgnoreApi = true)] 从我的 Swagger 中隐藏某些
在我的办公室,我们认为我们要将 Web.Config 的 AppSettings 放入数据库中。因此,我创建了以下内容,但对代码的几个方面有一些疑问。 所以我的问题是: UTILITY 类中包含“Ca
有人能帮我理解为什么在向配置文件添加值后,我不能立即将其读入应用程序吗?我做了刷新,但这不起作用。见下文: public void AddConfig(string key_value, st
我想从名为 MyAssembly.dll.config 的程序集配置文件中检索 AppSetting key 。这是配置文件的示例: 这是检索它的代码: va
我正在为 .NET 2.0 中的配置和设置类而苦苦挣扎 如果以下内容包含在名为 app.config 的文件中 我知道我可以通过以下方式访问 appSetting // this retur
我想从名为 secrets.config 的外部配置文件中读取控制台应用程序的 appSettings 的一部分,而其余部分我想从 app.config 中读取。 目前,我已经设置好了,但它似乎没有从
我有一个配置文件 app.exe.config 和 appSettings 部分有这样的东西: app.file.config 文件有这样的东西: 我需要在运行时
我目前正在从事 asp.net core (c#) Web API 项目。 对 Web API 的每次调用都将有一个唯一的 key ,以帮助识别进行调用的用户。 每个调用者都会有一组特定的配置值与之关
我是一名优秀的程序员,十分优秀!