使用Unity解析通用Microsoft.Extensions.Logging.ILogger <t>-获取InvalidCastException

时间:2019-04-08 12:03:53

标签: c# unity-container serilog .net-core-logging

我正在尝试在Unity(版本4)中注册通用ILogger(来自Microsoft.Extensions.Logging,而不是来自Serilog)。

我有以下课程:

public class MyClass
{
    private readonly Microsoft.Extensions.Logging.ILogger<MyClass> _logger;

    public MyClass(Microsoft.Extensions.Logging.ILogger<MyClass> logger)
    {
        _logger = logger;
    }
}

以及以下Unity注册和测试:

// Arrange
IUnityContainer container = new UnityContainer();

// provider from Serilog.Extensions.Logging nuget package
var provider = new Serilog.Extensions.Logging.SerilogLoggerProvider();

container.RegisterType(typeof(Microsoft.Extensions.Logging.ILogger<>),
    new InjectionFactory((ctr, type, name) =>
    {
        var loggerType = type.GetGenericArguments()[0].FullName;
        Microsoft.Extensions.Logging.ILogger logger = provider.CreateLogger(loggerType);
        return logger;
    }));

container.RegisterType<MyClass, MyClass>(); // just for demo purpose. 

// Assert
container.Resolve<MyClass>();

这对我来说似乎还可以,很糟糕,我在解决该错误时遇到以下错误:

  

异常是:InvalidCastException-无法将类型为'Serilog.Extensions.Logging.SerilogLogger'的对象转换为类型为'Microsoft.Extensions.Logging.ILogger`1 [MyNamespace.MyClass]'。

如何解决此问题?

完全例外:

  

Microsoft.Practices.Unity.ResolutionFailedException:依赖关系的解析失败,请键入=“ MyNamespace.MyClass”,名称=“(none)”。   发生以下异常:解析构造函数MyNamespace.MyClass(Microsoft.Extensions.Logging.ILogger 1[[MyNamespace.MyClass, MyNamespace.Infra.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=edbaf8e9a324553f]] logger). Exception is: InvalidCastException - Unable to cast object of type 'Serilog.Extensions.Logging.SerilogLogger' to type 'Microsoft.Extensions.Logging.ILogger 1 [MyNamespace.MyClass]'的参数“记录器”。

更新

使用Microsoft.Extensions.DependencyInjection时,此方法有效:

// Arrange
var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection()
    .AddLogging(builder => builder.AddSerilog())
    .AddTransient<MyClass, MyClass>();

var serviceProvider = serviceCollection.BuildServiceProvider();

// Assert
serviceProvider.GetService<MyClass>();

所以我尝试使用Unity而不是Microsoft.Extensions.DependencyInjection

不幸的是,Unity没有AddSerilog,我已经绑定到Unity

3 个答案:

答案 0 :(得分:1)

我找到的最简单的方法是注册工厂并反映他们的扩展方法以执行此操作并获取正确的响应类型。此示例还期望您已经注册了ILoggerFactory。

_container = new UnityContainer();
_container.RegisterInstance<ILoggerFactory>(new LoggerFactory().AddLog4Net(), new ContainerControlledLifetimeManager());
_container.RegisterFactory(typeof(ILogger<>), null, (c, t, n) =>
        {
            var factory = c.Resolve<ILoggerFactory>();
            var genericType = t.GetGenericArguments().First();
            var mi = typeof(Microsoft.Extensions.Logging.LoggerFactoryExtensions).GetMethods().Single(m => m.Name == "CreateLogger" && m.IsGenericMethodDefinition);
            var gi = mi.MakeGenericMethod(t.GetGenericArguments().First());
            return gi.Invoke(null, new[] { factory });
        });

答案 1 :(得分:1)

由于已经存在一个将ILoggerFactory作为依赖项的Logger 实现,因此您可以执行

container.RegisterType<ILoggerFactory, MyLoggerFactory>();
container.RegisterType(typeof(ILogger<>), typeof(Logger<>));
container.Resolve<ILogger<MyClass>>();

答案 2 :(得分:0)

I resolved this with the help of MakeGenericMethod and a helper method:

private static ILogger<T> CreateLogger<T>(ILoggerFactory factory)
{
    return new Logger<T>(factory);
}

And the final code (without reflection caching etc):

// Arrange
IUnityContainer container = new UnityContainer();

var logfactory = new LoggerFactory();

var provider = new Serilog.Extensions.Logging.SerilogLoggerProvider();
logfactory.AddProvider(provider);

container.RegisterType(typeof(Microsoft.Extensions.Logging.ILogger<>),
    new InjectionFactory((ctr, type, name) =>
    {
        var loggerType = type.GetGenericArguments()[0];

        var myType = this.GetType();

        var createLoggerMethod1 = myType.GetMethod(nameof(CreateLogger),BindingFlags.Static | BindingFlags.NonPublic);

        var createLoggerMethod = createLoggerMethod1.MakeGenericMethod(loggerType);

        var logger = createLoggerMethod.Invoke(this, new object[] {logfactory});

        return logger;
    }));

container.RegisterType<MyClass, MyClass>();

// Assert
container.Resolve<MyClass>();