Unity无法通过xml配置加载泛型类型定义 [英] Unity fails to load generic type definition via xml configuration
问题描述
我遇到了通过XML配置配置Unity 3.0的一些问题。解析泛型将给我下面的异常消息:
I'm running into some problems configuring Unity 3.0 via XML configuration. Resolving the generic type will give me the following exception message:
类型INLog`1没有可访问的构造函数。
The type INLog`1 does not have an accessible constructor.
以下是我的日志记录类的布局:
Here's the layout for my logging classes:
namespace Common.Utils.Logging {
public interface INLog
{
}
public interface INLog<T> : INLog where T : class
{
}
public class NLog : INLog
{
public NLog(Type type)
{
}
}
public class NLog<T> : NLog, INLog<T>
where T : class
{
public NLog()
: base(typeof(T))
{
}
}
}
我用这个XML代码注册泛型类型:
I register the generic type with this XML code:
<type type="Common.Utils.Logging.INLog[], Common.Utils" mapTo="Common.Utils.Logging.NLog[], Common.Utils" />
加载这个配置会给我下面的容器注册信息:
Loading this configuration gives me the following container registration:
LifetimeManager: {Microsoft.Practices.Unity.TransientLifetimeManager}
LifetimeManagerType: {Name = "TransientLifetimeManager" FullName = "Microsoft.Practices.Unity.TransientLifetimeManager"}
MappedToType: {Name = "NLog[]" FullName = "Common.Utils.Logging.NLog[]"}
Name: null
RegisteredType: {Name = "INLog[]" FullName = "Common.Utils.Logging.INLog[]"}
而不是我期望的注册,即:
Instead of the registration I'm expecting, namely:
LifetimeManager: null
LifetimeManagerType: {Name = "TransientLifetimeManager" FullName = "Microsoft.Practices.Unity.TransientLifetimeManager"}
MappedToType: {Name = "NLog`1" FullName = "Common.Utils.Logging.NLog`1"}
Name: null
RegisteredType: {Name = "INLog`1" FullName = "Common.Utils.Logging.INLog`1"}
在代码中注册工作得很好,并给出预期的注册:
Registering in code works just fine and gives the expected registration:
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType(typeof(INLog<>), typeof(NLog<>));
}
但我无法通过配置文件正确加载它。
我想这与非泛型类型(I)NLog的继承...
But I can't manage to get it loaded correctly via the configuration file. I guess this has to to with the inheritance of the non-generic types (I)NLog...
有没有人知道如何修复这是什么?
Does anyone of you guys know how to fix this?
最好的问候,
里克
Best regards, Rick
推荐答案
试试这个,而不是 []
记法
Try this instead of the []
notation
<type type="Common.Utils.Logging.INLog`1, Common.Utils" mapTo="Common.Utils.Logging.NLog`1, Common.Utils" />
感觉尴尬,我知道,但它应该可以工作。
Feels awkward, I know, but it should work.
这篇关于Unity无法通过xml配置加载泛型类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!