加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用configSource转换包含的配置文件

发布时间:2020-12-15 07:56:30 所属栏目:百科 来源:网络整理
导读:这个问题有点像两个人.在VS2015中,我的MVC项目有多种不同的构建配置,Test,UAT,Live等.使用我的web.config,我只需右键单击它并选择Add Config Transform即可为每个构建配置创建转换文件. 如果我有一个外部配置文件,例如Log4Net.config,我如何配置它以具有web.
这个问题有点像两个人.在VS2015中,我的MVC项目有多种不同的构建配置,Test,UAT,Live等.使用我的web.config,我只需右键单击它并选择Add Config Transform即可为每个构建配置创建转换文件.

如果我有一个外部配置文件,例如Log4Net.config,我如何配置它以具有web.config等依赖转换?这是通过编辑project.csproj文件手动完成的吗?

其次,我有一个web.config文件:

<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
    </configSections>

    ...

    <log4net configSource="Log4Net.config" />
</configuration>

当我构建项目时,web.config会自动通过project.csproj文件中的以下AfterBuild目标进行转换:

<Target Name="AfterBuild">
    <TransformXml Source="Web.config"
            Transform="Web.$(Configuration).config"
            Destination="$(OutputPath)$(AssemblyName).config" />
</Target>

如何使用相同的配置转换转换包含的Log4Net.config文件?我意识到我可以将另一个TransformXml放入AfterBuild目标中,但这是进行此转换的正确方法,还是我错过了什么?

解决方法

我选择使用基本Log4Net.config文件,每个构建配置的Log4Net.XXX.config文件以及AfterBuild目标中的其他TransformXml任务的解决方案:

> Log4Net.config
> Log4Net.Debug.config
> Log4Net.Release.config
> Log4Net.Test.config
> Log4Net.UAT.config

project.csproj文件现在看起来像这样:

<Content Include="Log4Net.config">
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Include="Log4Net.Debug.config">
  <DependentUpon>Log4Net.config</DependentUpon>
</None>
<None Include="Log4Net.Release.config">
  <DependentUpon>Log4Net.config</DependentUpon>
</None>
<None Include="Log4Net.Test.config">
  <DependentUpon>Log4Net.config</DependentUpon>
</None>
<None Include="Log4Net.UAT.config">
  <DependentUpon>Log4Net.config</DependentUpon>
</None>

....

<Target Name="AfterBuild">
   <TransformXml Source="Web.config" Transform="Web.$(Configuration).config" Destination="$(OutputPath)$(AssemblyName).config" />
   <TransformXml Source="Log4Net.config" Transform="Log4Net.$(Configuration).config" Destination="$(OutputPath)Log4Net.config" />
</Target>

一个示例Log4Net.Test.config看起来像这样(我使用转换来更改连接字符串和Log4Net的日志记录级别):

<?xml version="1.0" encoding="utf-8"?>

<log4net  xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <appender>
        <connectionString
            value="Data Source=example.com;Initial Catalog=ExampleLogs;User ID=xxx;Password=xxx"
            xdt:Transform="Replace" />
    </appender>

    <root>
        <level
            value="DEBUG"
            xdt:Transform="Replace" />
    </root>
</log4net>

这会成功转换输出路径中的Log4Net.config文件.它使用与转换web.config文件相同的方法,因此任何其他开发人员都可以轻松理解它.

虽然这有效并且已经生产了一段时间,但我仍然在寻找一些确认,这是对包含的配置文件进行转换的正确方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读