如何在mvc4中分离调试和释放连接等

Ric*_*erg 2 deployment entity-framework release profiles release-management

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

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

所以例如我在我的repo(域项目)公共类EFAccountRepository中执行了这样的操作:IAccountRepository {private EFDbContext _context;

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

在我的DI(webui)中这样

#if DEBUG
        EFDbContext efcontext = new EFDbContext("name=Debug");
#else
        EFDbContext efcontext = new EFDbContext("name=Live");
#endif
Run Code Online (Sandbox Code Playgroud)

或者只是拥有它会更聪明

EFDbContext efcontext = new EFDbContext("name=MyApp");
Run Code Online (Sandbox Code Playgroud)

然后使用web.config转换MyApp的含义?

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

Jon*_*ear 5

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

ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString
Run Code Online (Sandbox Code Playgroud)

在调试版本中你可以有类似的东西

<configuration xmlns:xdt="...">
    <connectionStrings>
      <add name="MyConnectionString" connectionString="debugstring"
         providerName="debugprovider" />
     </connectionStrings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

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

<configuration xmlns:xdt="...">
    <connectionStrings>
      <add name="MyConnectionString" connectionString="newstring"
         providerName="newprovider"
         xdt:Transform="Replace" />
     </connectionStrings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

有关更多参考,请访问 http://msdn.microsoft.com/en-us/library/dd465326.aspx