.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之类的配置时才用得到,至少我是这个时候用的

posted @ 2017-01-09 17:10  麻将我会  阅读(705)  评论(0编辑  收藏  举报