Microsoft DI : Register generic Log4NetAdapter<> against non-generic ILog interface

Viewed 55

I am switching a project from SimpleInjector to Microsoft's built-in DI container. In this project, I have created a generic Log4NetAdapter class which I am registering into SimpleInjector's container against Log4Net's non-generic ILog interface like so :

container.RegisterConditional(typeof(ILog),
    c => typeof(Log4NetAdapter<>).MakeGenericType(c.Consumer.ImplementationType),
    Lifestyle.Singleton, c => true);

This allows my controllers to receive a non-generic ILog injection in their controllers. I am trying to achieve the same thing with Microsoft's built-in DI (Microsoft.Extensions.Hosting) and I am not sure how to proceed or if this is even possible. I have tried the following :

services.AddTransient(typeof(ILog), typeof(Log4NetAdapter<>));

The above code is throwing the following exception :

System.ArgumentException: 'Cannot instantiate implementation type 'SomeTool.Utilities.Log4NetAdapter`1[T]' for service type 'log4net.ILog'.'

Is there a way to get this to work with Microsoft's DI container?

Thanks

1 Answers

What you are trying to achieve is called Conditional Binding or Context-Based Injection and it is a feature that isn't supported by MS.DI and, due to its design, is impossible add.

More mature and feature rich DI Containers do support this feature, such as (but not limited to) Autofac, Ninject, and Simple Injector.

Related