Generics in Unity
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 (here string and int), maybe genericParameterName, but I don't know how to use it when there are 2 generics.
Thanks
解答
- 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;- 已標示為解答chrisqwer Wednesday, 22 April, 2009 13:06
所有回覆
- 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.
- 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;- 已標示為解答chrisqwer Wednesday, 22 April, 2009 13:06

