Question

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.

Was it helpful?

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

OTHER TIPS

The selected answer will not work if you have more than one connection string. in the release config add below tags for all your connectionstrings

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

This is what I have in my Web configuration files

in Web.Debug.Config

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

and in 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)"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top