在统一配置,如何的connectionString传递给一个构造函数? [英] In Unity config, how to pass connectionString to a constructor?

查看:125
本文介绍了在统一配置,如何的connectionString传递给一个构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设立在web.config中的统一配置和我有一个类型,我想传递给它它已经在相同的web.config文件中存在的连接字符串。

I am setting up the unity configurations in the web.config and I have a type which I want to pass to it the connection string which already exist in the same web.config file.

<connectionStrings>
    <add name="DatabaseConnectionString" connectionString="metadata=res://*/Database.csdl|res://*/Database.ssdl|....." providerName="System.Data.EntityClient" />
  </connectionStrings>

和在团结节还有是:

<type type="IDatabase" mapTo="Database" >
      <constructor>
          <param name="connectionString" >
             <value value="metadata=res://*/Database.csdl|res://*/Database.ssdl|...."/>
          </param>
      </constructor>
</type>

不过,像我在同一个config文件两次写入相同conectionString,是否有另一种更好的方式来传递ConnectionString,以数据库的类型构造,以避免在web.config中重复的只是名字?

But like that I am writing the same conectionString twice in the same .config file, Is there another better way to pass just the name of the connectionString to the type Database constructor to avoid duplicates in the web.config?

推荐答案

由克里斯·<一的建议你可以写你自己的类型转换器href=\"http://stackoverflow.com/questions/3178394/unity-pass-parameters-to-custom-lifetime-constructor-in-xml-configuration-file/3593827#3593827\">answering一个previous问题。

<type type="IDatabase" mapTo="Database" >
      <constructor>
          <param name="connectionString" >
             <value value="DatabaseConnectionString" typeConverter="ConnectionStringTypeConverter"/>
          </param>
      </constructor>
</type>

<一个href=\"http://msdn.microsoft.com/en-us/library/ff660914(v=PandP.20).aspx#config_value\">http://msdn.microsoft.com/en-us/library/ff660914(v=PandP.20).aspx#config_value

修改

该转换器应该工作:

public class ConnectionStringTypeConverter : TypeConverter
    {
      public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
      {
        return ConfigurationManager.ConnectionStrings[value.ToString()];
      }
    }

这篇关于在统一配置,如何的connectionString传递给一个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆