You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 4.8中使用Unity注入解析Microsoft Logger时抛出异常

.NET 4.8下Unity注册Microsoft.Logger后解析所有注册项报错的解决方法

问题场景

在.NET 4.8环境中,通过Unity容器注册Microsoft.Extensions.Logging组件,注册代码如下:

var factory = new LoggerFactory();
factory.AddLog4Net("log4net.config");
container.RegisterInstance<ILoggerFactory>(factory);
container.RegisterType(typeof(ILogger<>), typeof(Logger<>));

尝试遍历所有注册类型并解析时,抛出错误:

Resolving Microsoft.Extensions.Logging.ILogger`1[TCategoryName][],(none) ---> System.InvalidOperationException: Could not execute the method because either the method itself or the containing type is not fully instantiated.

解析代码如下:

foreach (var item in _unityContainer.Registrations)
{
    var named = _unityContainer.ResolveAll(item.RegisteredType);
    if (_unityContainer.IsRegistered(item.RegisteredType))
    {
        var tmp = _unityContainer.Resolve(item.RegisteredType);
    }
}

错误原因

问题出在未绑定泛型类型ILogger<>的处理上:Unity的Registrations集合会包含ILogger<>这种未绑定的泛型定义(没有指定具体类型参数的泛型),而Resolve方法无法直接解析这类类型——因为它需要具体的类型参数(比如ILogger<MyService>)才能实例化,直接解析未绑定泛型就会触发上述错误。

解决方案

修改解析逻辑,跳过未绑定的泛型类型,只处理可直接实例化的类型:

foreach (var item in _unityContainer.Registrations)
{
    var registeredType = item.RegisteredType;
    // 跳过未绑定的泛型类型(如ILogger<>)
    if (registeredType.IsGenericTypeDefinition)
    {
        continue;
    }

    var named = _unityContainer.ResolveAll(registeredType);
    if (_unityContainer.IsRegistered(registeredType))
    {
        var tmp = _unityContainer.Resolve(registeredType);
    }
}

补充说明

  • 未绑定泛型类型的判断依据是Type.IsGenericTypeDefinition属性为true,这类类型不能直接被解析,必须指定具体的类型参数才能生成可实例化的泛型类型。
  • 若需要使用泛型日志组件,应该针对具体的泛型实例(比如ILogger<MyService>)进行依赖注入,而非直接操作未绑定的泛型定义。

内容的提问来源于stack exchange,提问作者pakerinjo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 13:07:14