how to resolve a object which constructor's parameter depends on a static class method's return value

Jul 1, 2010 at 2:33 AM

i'd like to  use the app.config to register types,some thing like this:

          <type type="ISiteOpInfoRepository" mapTo="SiteOpInfoRepository">
            <lifetime type="PerWebRequest" />
                <param name="connectionString" parameterType="System.String">
                  <dependency name="chengduDatabase" />
          <add name="chengduDatabase" type="System.String" value="Data base Connection String">
          <add type="Putao.Framework.UnityExetnsion.PolicyInjectionExtension,Putao.Framework.UnityExetnsion">

after config this, i can use the DependencyAttribute to property injection,

it works fine when the the chengduDatabase' value is a const string, but what if the connection string is returned by a static method, eg. ConnectionStringManager.GetCurrentWhConn(), how can i set the config to use the value return by GetCurrentWhConn method?

Jul 1, 2010 at 7:11 AM

There's no direct way to configure the static method in the configuration but you can make use of the typeConverter attribute and create your own class that inherits from the TypeConverter class.  Override the ConverTo method and within that method, call the static method.


public class MyTypeConverter : System.ComponentModel.TypeConverter
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
            return ConnectionStringManager.GetCurrentWhConn();

Your configuration would then look like:

<param name="connectionString" parameterType="System.String">
      <value value="" typeConverter="Common.MyTypeConverter, Common" />

The value of the typeConverter attribute should be the fully qualified name of your custom type converter class, or an alias.  Also note that the value you entered in the value attribute is passed to the value parameter of the ConvertTo method so you can use it if you need certain information from the configuration in order to be able to return the correct value.


Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc. 

Jul 23, 2010 at 3:43 AM

hi, sarah,

i tried to use the typeConvert, but it doesn't work, the connectionString parm alwasy been set to "" if i set value="", it seemed the unity totaly ignored the typeConverter

i'm using unity 1.2 , any suggestions?

Jul 26, 2010 at 2:28 AM

My apologies, I forgot that the typeConverter attribute is being ignored if the parameter type is set to string.  The easiest workaround would be to change the type of the connectionString parameter replacing it with a custom class with a single property to contain the actual value of the connection string.  Another possibility would be to implement something like what is described in this post.


Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.