How to separate between debug and release for connections etc in mvc4

deployment, entity-framework, profiles, release, release-management

Solution

I would strongly recommend not hardcoding your connection strings into your code. Please consider pointing your code to a web.config transform. You can add the connection string there and depending on the version of code the proper transform can be applied so that you simply need to use the following code once in your app to cover all environments.

ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString

Inside of the debug version you could have something similar to

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

Inside your release version you can tell the transform to replace your old string as so

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

for more reference check out http://msdn.microsoft.com/en-us/library/dd465326.aspx

Problem

So I am fairly new MVC4 and many patterns are new to me. However the one thing I am curious about is best practice about release/debug modes. There are a bunch of things for me that differ between live and debug mode and I would like for all of them to be automatic so I don't need to change anything to publish. So for instance I have done like this in my repo (domain project) public class EFAccountRepository : IAccountRepository { private EFDbContext _context; ``` public EFAccountRepository() { #if DEBUG _context = new EFDbContext("name=Debug"); #else _context = new EFDbContext("name=Live"); #endif } ``` and like this in my DI (webui) ``` #if DEBUG EFDbContext efcontext = new EFDbContext("name=Debug"); #else EFDbContext efcontext = new EFDbContext("name=Live"); #endif ``` Or would it be smarter to simply have ``` EFDbContext efcontext = new EFDbContext("name=MyApp"); ``` And then change with web.config transform what MyApp means? Any other tips of automating debug/release-publish is warmly welcomed.

Original source