I have the following class:
public class TestInjection
{
private ILogger logger;
public TestInjection(ILogger logger)
{
this.logger = logger;
}
public void Process()
{
try
{
int zero = 0;
int result = 5 / zero;
}
catch (DivideByZeroException ex)
{
logger.Log(LogLevel.Error, "test message", ex);
Console.WriteLine("logged message from class");
}
}
}
And in my Program.cs
I have the code:
IUnityContainer container = new UnityContainer();
container.RegisterType<TestInjection>();
var myTestClass = container.Resolve<TestInjection>(new ResolverOverride[] { new ParameterOverride("logger", LogManager.GetCurrentClassLogger()) });
myTestClass.Process();
How to resolve LogManager.GetCurrentClassLogger()
with the unity container, if the default constructor of the Logger
class it's not accessible?
PS: This is my first experience with DI and Unity.
Here is how I've done:
IUnityContainer container = new UnityContainer();
container.RegisterType<ILogger>(
new InjectionFactory(l => LogManager.GetCurrentClassLogger()));
container.RegisterType<TestInjection>();
var myTestClass = container.Resolve<TestInjection>(
new ResolverOverride[]
{
new ParameterOverride("logger", container.Resolve<ILogger>())
});
myTestClass.Process();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With