开发者

In Unity config, how to pass connectionString to a constructor?

开发者 https://www.devze.com 2023-01-26 23:56 出处:网络
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.

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>

and in the unity section there is:

<type type="IDatabase" mapTo="Database" >
      <constructor>
          <param name="connectionString" >
             <value value="met开发者_如何学运维adata=res://*/Database.csdl|res://*/Database.ssdl|...."/>
          </param>
      </constructor>
</type>

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?


You could write your own TypeConverter as suggested by Chris answering a previous question.

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

http://msdn.microsoft.com/en-us/library/ff660914(v=PandP.20).aspx#config_value

EDIT

This converter should work:

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


There's nothing built in to do this. You can write a schema extension that will do something along these lines, but it's not a well documented process at the moment. I'll see if I can come up with an example later.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号