【问题标题】:Unity fails to load generic type definition via xml configurationUnity 无法通过 xml 配置加载泛型类型定义
【发布时间】:2013-09-12 14:12:37
【问题描述】:

我在通过 XML 配置配置 Unity 3.0 时遇到了一些问题。解析泛型类型会给我以下异常消息:

INLog`1 类型没有可访问的构造函数。

这是我的日志记录类的布局:

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 代码注册了泛型:

<type type="Common.Utils.Logging.INLog[], Common.Utils" mapTo="Common.Utils.Logging.NLog[], Common.Utils" />

加载此配置会为我提供以下容器注册:

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[]"}

而不是我期望的注册,即:

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"}

在代码中注册可以正常工作并提供预期的注册:

using (IUnityContainer container = new UnityContainer())
{
    container.RegisterType(typeof(INLog<>), typeof(NLog<>));
}

但我无法通过配置文件正确加载它。 我想这与非泛型类型 (I)NLog 的继承有关...

你们中有人知道如何解决这个问题吗?

最好的问候, 瑞克

【问题讨论】:

    标签: c# xml generics unity-container


    【解决方案1】:

    试试这个而不是[] 表示法

    <type type="Common.Utils.Logging.INLog`1, Common.Utils" mapTo="Common.Utils.Logging.NLog`1, Common.Utils" />
    

    感觉很尴尬,我知道,但应该可以。

    【讨论】:

    • 谢谢,解决了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多