wal*_*_dl 3 c# msbuild csproj .net-core asp.net-core-2.0
我想获取使用C#的<Location>SourceFiles/ConnectionStrings.json</Location>子元素的值<PropertyGroup />。该文件位于.NET Core 2 classlib项目的.csproj文件中。结构如下:
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<Location>SharedSettingsProvider.SourceFiles/ConnectionStrings.json</Location>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)
我可以使用.NET Core库中的哪个类来实现这一目标?(不是.NET Framework)
更新1: 我想在应用程序(此.csproj文件生成)运行时读取值。部署之前和之后。
谢谢
正如评论中所讨论的那样,csproj内容仅控制预定义的构建任务,并且在运行时不可用。
但是msbuild很灵活,可以使用其他方法将某些值持久化以在运行时可用。
一种可能的方法是创建自定义程序集属性:
[System.AttributeUsage(System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
sealed class ConfigurationLocationAttribute : System.Attribute
{
public string ConfigurationLocation { get; }
public ConfigurationLocationAttribute(string configurationLocation)
{
this.ConfigurationLocation = configurationLocation;
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以在csproj文件内部的自动生成的程序集属性中使用它:
<PropertyGroup>
<ConfigurationLocation>https://my-config.service/customer2.json</ConfigurationLocation>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="An.Example.ConfigurationLocationAttribute">
<_Parameter1>"$(ConfigurationLocation)"</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)
然后在运行时在代码中使用:
static void Main(string[] args)
{
var configurationLocation = Assembly.GetEntryAssembly()
.GetCustomAttribute<ConfigurationLocationAttribute>()
.ConfigurationLocation;
Console.WriteLine($"Should get config from {configurationLocation}");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2081 次 |
| 最近记录: |