3

所以我是相当新的 MVC4,许多模式对我来说都是新的。

然而,我很好奇的一件事是关于发布/调试模式的最佳实践。对我来说,实时模式和调试模式之间有很多不同之处,我希望它们都是自动的,所以我不需要更改任何内容即可发布。

因此,例如,我在我的 repo(域项目)公共类 EFAccountRepository 中做了这样的事情: IAccountRepository { private EFDbContext _context;

    public EFAccountRepository()
    {
#if DEBUG
        _context = new EFDbContext("name=Debug");
#else
        _context = new EFDbContext("name=Live");
#endif
    }

在我的 DI (webui) 中像这样

#if DEBUG
        EFDbContext efcontext = new EFDbContext("name=Debug");
#else
        EFDbContext efcontext = new EFDbContext("name=Live");
#endif

或者简单地拥有会更聪明吗

EFDbContext efcontext = new EFDbContext("name=MyApp");

然后用 web.config 改变 myApp 是什么意思?

任何其他自动化调试/发布发布的技巧都受到热烈欢迎。

4

3 回答 3

6

我强烈建议不要将连接字符串硬编码到代码中。请考虑将您的代码指向 web.config 转换。您可以在此处添加连接字符串,并根据代码版本应用适当的转换,因此您只需在应用程序中使用以下代码一次即可覆盖所有环境。

ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString

在调试版本中,您可能会有类似的东西

<configuration xmlns:xdt="...">
    <connectionStrings>
      <add name="MyConnectionString" connectionString="debugstring"
         providerName="debugprovider" />
     </connectionStrings>
</configuration>

在您的发布版本中,您可以告诉转换替换旧字符串

<configuration xmlns:xdt="...">
    <connectionStrings>
      <add name="MyConnectionString" connectionString="newstring"
         providerName="newprovider"
         xdt:Transform="Replace" />
     </connectionStrings>
</configuration>

如需更多参考,请查看 http://msdn.microsoft.com/en-us/library/dd465326.aspx

于 2013-03-29T17:59:12.523 回答
4

如果您有多个连接字符串,则所选答案将不起作用。在发布配置中为所有连接字符串添加以下标签

xdt:Transform="SetAttributes" xdt:Locator="Match(name)"

这就是我的 Web 配置文件中的内容

在 Web.Debug.Config

<add name="MyConnectionString" 
    connectionString="Data Source=dev;Initial Catalog=DevDB;Integrated Security=True;
    providerName="System.Data.SqlClient"/>

并在 Web.Release.Config

<add name="MyConnectionString" 
    connectionString="Data Source=LIVESERVER;Initial Catalog=DB98;Integrated Security=True;
    providerName="System.Data.SqlClient" 
    xdt:Transform="SetAttributes" 
    xdt:Locator="Match(name)"/>
于 2014-08-19T17:56:04.523 回答
1

使用 web.config 转换http://msdn.microsoft.com/en-us/library/dd465326.aspx

于 2013-03-29T17:14:40.767 回答