tags:

views:

84

answers:

1

How to register an instance in congif file

I am having this code

UnityContainer.RegisterInstance<ICache>(new CacheMng(HttpRuntime.Cache));

And trying to have the equivalent in a config file

<register type="ICache"           mapTo="CacheMng">
 <lifetime type="Singleton"/>
   <constructor>
            <param name="cache"  type="System.Web.Caching"   value="HttpRuntime.Cache"/>
   </constructor>>
</register>

My CacheMng class has this contructor

public CacheMng(Cache cache)
{
    this._cache = cache
}

I'm getting this error

The type name or alias System.Web.Caching could not be resolved

A: 

The reason you get the error message you see is that the type parameter requires a type name and not a namespace name. System.Web.Caching is a namespace and not a type.

The only way to do this is to write a custom type converter and use the value element, like this:

<constructor>
    <param name="cache">
        <value value="" typeConverter="MyHttpRuntimeCacheConverter" />
    </param>
</constructor>

The type converter looks something like this (in its simplest form):

public class MyHttpRuntimeCacheConverter : System.ComponentModel.TypeConverter
{
    public override object ConvertTo(ITypeDescriptorContext context,
                                     CultureInfo culture, object value,
                                     Type destinationType)
    {
        return HttpRuntime.Cache;
    }
}

You could make this more generally applicable by actually providing a value for the Unity value element (for example: System.Web.HttpRuntime.Cache) and based on this value have the type converter return the right object.

Ronald Wildenberg