Asp Net MVC pass connection string to access layer

0

I have a project that is divided into layers, BLL DAL and UI, in the UI is my MVC project, however the need arose on the login screen the user choose the connection string, how can I pass this string from the MVC project for DAL and continue to use every time I instantiate DbContext?

    
asked by anonymous 19.02.2016 / 19:45

3 answers

2

Follows a solution using Singleton Design Pattern

using System;

// Exemplo singleton        
public sealed class ConnectionStringManager
{
    #region Singleton design pattern properties
    private static readonly Lazy<ConnectionStringManager> lazy =
        new Lazy<ConnectionStringManager>(() => new ConnectionStringManager());
    public static ConnectionStringManager Instance { get { return lazy.Value; } }
    private ConnectionStringManager(){ }
    #endregion

    public string CurrentConnectionString { get; set; }

}

// Exemplo de console application
public class Program
{
    public static void Main()
    {
        // Setando a connection string
        ConnectionStringManager.Instance.CurrentConnectionString = "connectionstring selecionado pelo cliente";
        // Voce vai poder acessar a propriedade novamente utilizando 
        // "ConnectionStringManager.Instance.CurrentConnectionString"
        // em qualquer outra classe do sistema.
        Console.WriteLine(ConnectionStringManager.Instance.CurrentConnectionString);
    }
}

If you understand a little English I recommend reading the article: link

    
22.02.2016 / 02:42
2

Another alternative to doing this is also using hack to change the read-only parameter ConfigurationManager.ConnectionStrings , this solution found on the link , thus:

var settings = ConfigurationManager.ConnectionStrings["nomeDaMinhaConexao"];
var fi = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(settings, false);
settings.ConnectionString = "minhaStringDeConexao";

I put the connection string and it was giving the error Keyword not supported: “data source” , to correct it is just to change where it has &quot; in the connection string for single quotation marks.

Remembering that it's a hack , but I've done a lot of testing here and the application is working normally.

    
22.02.2016 / 19:00
1

Just add the ConnectionStrings in your web.config.

Only list the connection names on the login screen.

Then you can persist the selected name in a Session , and in the other layers you refer to the System.Web library and retrieve the selected name.

And also in its other layers, you refer to the System.Configuration library and retrieve the connection string with ConfigurationManager.ConnectionStrings["nome"] .

But all this is a bad practice.

If you want to point to distinct environments, do so with Web.Config Transformations .

    
19.02.2016 / 19:52