• .net 实战 根据configuration选项生成不同的config文件


    项目开发过程中都会遇到的问题,开发环境的配置肯定是和生产环境不一样的,
    一直都是重复手动拷贝,但是配置太多拷贝的弊端就显现出来了,
    为了解决这个问题可以有几种方案:

    1.Web.config Transformation

    Transformation的相关知识点可以参考下面的文章,

    这个东西有个不好的地方,就是只有在publish的时候才执行,在开发调试期间是不起作用的,

    所以一般应用在网站发布期间

    https://msdn.microsoft.com/en-us/library/dd465326(v=vs.110).aspx

    http://www.cnblogs.com/worksguo/archive/2009/08/29/1556307.html


    2.MSBuild 在BuildBefore事件中应用XslTransformation

     示例代码: https://github.com/xlb378917466/MSBuild_BuildBefore

    知识点学习:http://www.cnblogs.com/shanyou/p/3452938.html

    这个功能很强大,这里使用了BuildBefore事件,这样在开发调试期间就可以获取到修改之后的配置,

        <Target Name="BeforeBuild">
        <XslTransformation Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'" XslInputPath="Debug.xslt" XmlInputPaths="WebTemplate.config" OutputPaths="Web.config" />
        <XslTransformation Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'" XslInputPath="Release.xslt" XmlInputPaths="WebTemplate.config" OutputPaths="Web.config" />
      </Target>

    这里定义了两个xslt文件用来输出最终的web.config文件,当然你要自己定义一个原始的输入文件WebTemplate.config,

    这个例子简单的APPSetting中的值根据实际的Configuration进行修改

    <appSettings>
        <add key="Mode" value="Release" />
      </appSettings>
    

     Debug.Xslt

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" />
     <xsl:template match="@*|node()">
       <xsl:copy>
         <xsl:apply-templates select="@*|node()" />
       </xsl:copy>
     </xsl:template>
    <xsl:template match="/configuration/appSettings/add[@key='Mode']">
     <add key="Mode" value="Debug"/>
    </xsl:template>
    </xsl:stylesheet>
    

     Release.Xslt

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" />
     <xsl:template match="@*|node()">
       <xsl:copy>
         <xsl:apply-templates select="@*|node()" />
       </xsl:copy>
     </xsl:template>
    <xsl:template match="/configuration/appSettings/add[@key='Mode']">
     <add key="Mode" value="Release"/>
    </xsl:template>
    </xsl:stylesheet>

    3.通过Symbols(条件编译)来使用C#代码控制

      参考之前的一篇文章:条件编译  

    这种做法一般是在加载其他XML之类的配置时才用得到,至少我是这个时候用的

  • 相关阅读:
    asp.net mvc 中使用async/await异步编程
    简述C#中浅复制和深复制
    Angular:自定义表单控件
    Angular:Reactive Form的使用方法和自定义验证器
    Angular:ViewProviders和Providers的区别
    Angular:OnPush变化检测策略介绍
    Angular:利用内容投射向组件输入ngForOf模板
    在Angular中利用trackBy来提升性能
    Angular @HostBinding()和@HostListener()用法
    Angular利用@ViewChild在父组件执行子组件的方法
  • 原文地址:https://www.cnblogs.com/LittleFeiHu/p/6265908.html
Copyright © 2020-2023  润新知