Unity and Generics

Apr 7, 2009 at 10:22 AM
Hello,

I have a question about Unity and the Generics, and I don't know which forum I should post my question. Hope you will be able to help me or redirect my question.

I have a caching manager, here are the interface and the class that implement the interface:
public interface ICacheMgr<TKey, TValue>
public class CacheMgr<TKey, TValue> : ICacheMgr<TKey, TValue>, IDisposable

Now I configure them in my app.config:

<type name="CachingMgr"
 type="Acm.Esb.Service.ICacheMgr`2, Acm.Esb.Service"
 mapTo="Acm.Esb.Service.CacheMgr`2, Acm.Esb.Service">
 <typeConfig>
 [...]
 </typeConfig>
</type>

Now I try to instantiate a CaheMgr
ICacheMgr<string, int> foo = ((ICacheMgr<string, int>)ServiceContainer.Resolve<ICacheMgr<string, int>>("CachingMgr", "production"));
It is running fine.

Now, I want to inject object ICacheMgr in another service:
public interface ICacheService
{
 ICacheMgr<string, int> CacheMgr { get; set; }
}

public class CacheService : ICacheService
{
 public ICacheMgr<string, int> CacheMgr { get; set; }
}


<type name="CachingService"
 type="ConsoleApplication1.ICacheService, ConsoleApplication1"
 mapTo="ConsoleApplication1.CacheService, ConsoleApplication1">
 <typeConfig>
  <property name="CacheMgr"
  propertyType="Acm.Esb.Service.ICacheMgr`2, Acm.Esb.Service">
   <dependency  name="CachingMgr"/>
  </property>
 </typeConfig>
</type>

I don't know how to specify the type of TValue and TKey type in the config file (here string and int), maybe genericParameterName, but I don't know how to use it when there are 2 generics.

Thanks
Apr 21, 2009 at 12:02 PM
I'm currently looking into using Unity and have run into the same problem. I don't think it is genericParameterName, since you can only use it in constructors, properties and methods.
Apr 21, 2009 at 12:25 PM
Edited Apr 21, 2009 at 12:26 PM
After some digging I just found the solution, you should be able to use something like this:
<property name="CacheMgr" propertyType="Acm.Esb.Service.ICacheMgr`2[[System.String, mscorlib],[System.Int32, mscorlib]], Acm.Esb.Service">
If you're not sure what type you can use you can just create an instance of the class and get the type from it:
Dictionary<string, int> d = new Dictionary<string, int>();
string t = d.GetType().FullName;