Dependency Injection and Log4Net
I need to add two different log methods on my app.
Now, to add a normal Log4net in DI we can do this (microsoft unity):
container.AddNewExtension<Log4NetExtension>();
This is by using Log4NetExtension.cs. Now as I need to add a new one append
container.AddNewExtension<NewLog4NetExtension>();
So, I tried to override "Log4NetExtension"
public interface ILogExtender : ILog { } [SecuritySafeCritical] public class NewLog4NetExtension: UnityContainerExtension { protected override void Initialize() { Context.Policies.Set(typeof(ILogExtender), typeof(ResolveDelegateFactory), (ResolveDelegateFactory)GetResolver); } public ResolveDelegate<BuilderContext> GetResolver(ref BuilderContext context) { return (ref BuilderContext c) => LogManager.GetLogger("AuthenticationLog"); } }
And then, add this to the DI container: //original container.AddNewExtension(); //new logger container.AddNewExtension();
But then… I get this:
Object of type ‘log4net.Core.LogImpl’ cannot be converted to type ‘Accredit.Commons.Log4Net.ILogExtender’. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
What am i doing wrong? Any help ?
I end up by doing this:
public interface ILogExtender { ILog Log { get; set; } }
//interface implementation:
public class LogExtender : ILogExtender { public ILog Log { get; set; } }
[SecuritySafeCritical] public class SomeExtensionLog4NetExtension : UnityContainerExtension { protected override void Initialize() { Context.Policies.Set(typeof(ILogExtender), typeof(ResolveDelegateFactory), (ResolveDelegateFactory)GetResolver); } public ResolveDelegate<BuilderContext> GetResolver(ref BuilderContext context) { return (ref BuilderContext c) => new LogExtender() { Log = LogManager.GetLogger("AuthenticationLog") }; } }
Note the need to implement the new interface and set the ILog from Logmanager to it. It’s a bit dirty – but is working.
this endup usefull as it allows me to had two diferent ways of using log4net – which was a request as i need to write de default logs to one place and specifics to another.