【问题标题】:How to apply IoC in Development db connection string and Production Db connection string settings如何在开发数据库连接字符串和生产数据库连接字符串设置中应用 IoC
【发布时间】:2011-01-20 04:40:16
【问题描述】:

谁能提供一个使用 IoC(structureMap / Spring.Net)在开发和生产中的数据访问层交换连接字符串的示例? (如果可能,在 C# 中)

谢谢

【问题讨论】:

  • 为什么要为此使用 IoC?使用配置参数。
  • 谢谢 yodaj,我完全同意你的看法。但是有什么方法可以为此应用 IoC 吗?如果是这样,我想知道它是如何完成的。

标签: c# database connection-string ioc-container


【解决方案1】:

不了解 Spring.Net,但我通常在 ASP.Net 中这样做,假设您有一个接受数据库连接字符串的 DAL。

<connectionStrings>
    <add name="Development" connectionString="Enlist=false;MultipleActiveResultSets=True;Data Source=MYPC\SQLEXPRESS;Initial Catalog=Development;Integrated Security=True" providerName="System.Data.SqlClient"/>
    <add name="Production" connectionString="Enlist=false;MultipleActiveResultSets=True;Data Source=MYPC\SQLEXPRESS;Initial Catalog=Production;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

public class MySession : ISession
{
    public MySession(string connectionName)
    {
        // ...
    }
}

ObjectFactory.Initialize(
    x =>
    {
         x.For<ISession>()
          .Use<MySession>().Ctor<string>("connectionName").Is("Development");
          //.Use<MySession>().Ctor<string>("connectionName").Is("Production");
    }

【讨论】:

    【解决方案2】:

    如果我是你,我不会那样做

    1. 部署时,所有环境的连接字符串都将发送到所有环境(安全问题)
    2. 您偏离了标准实现,从长远来看这意味着痛苦

    但如果你真的需要,你可能不得不做这样的事情:(这甚至可能行不通)

    <db:provider id="PRODDbProvider" provider="SqlServer-2.0" connectionString="whateveritis" />
    
    <db:provider id="DEVDbProvider" provider="SqlServer-2.0" connectionString="whateveritis" />
    
    <object id="genericAdoTemplate" type="CustomAdoTemplate">
    <property name="DbProviders">
      <dictionary>
        <entry key="PROD" value="PRODDbProvider" />
        <entry key="DEV" value="DEVDbProvider" />
      </dictionary>
    </property>
    </object>
    

    然后有一个自定义的 AdoTemplate

    public class CustomAdoTemplate : Spring.Data.Generic.AdoTemplate {
    
        public object DbProviders {
            get;
            set;
        }
    
        public override object DbProvider {
            get {
                return DbProviders[GetCurrentEnvironmentKey()];
            }
        }
    }
    

    【讨论】:

    • 谢谢!杰格。 1)你的意思是所有层? 2) 你能详细说明一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多