Ultimately this has to do with setting up log4Net but generically the problem is not logging specific.
Generically what I am trying to figure out is how to do, in Microsoft Unity 2.0, something equivalent to what one gets with the Castle.Facilities.Logging.LoggingFacility. Namely the ability to declare a dependency on a logger and have the logger initialized with the Type of the object into which it is being injected.
In the spirit of a test is worth a thousand words, here is what I need:
class Logger_IOC_Tests { //[Test] public void Logger_should_be_initialized_with_the_type_of_the_object_that_is_using_it() { var container = new UnityContainer(); /* Configuration Magic probably involiving registering either * a custom IDependencyResolverPolicy or BuilderStrategy * goes here... */ container.RegisterType<LoggerUser>(new ContainerControlledLifetimeManager()); var user = container.Resolve<LoggerUser>(); Assert.True(user.Logger.GetUserType() == user.GetType()); } } interface ILogger { Type GetUserType(); } class Logger : ILogger { private readonly Type _type; public Logger(Type type) { _type = type; } public Type GetUserType() { return _type; } } class LoggerUser { public readonly ILogger Logger; public LoggerUser(ILogger logger) { Logger = logger; } }
I don't know if this what you are looking for, but I saw it a few months ago and was reminded of it when I saw your question. I have not used Unity, so I can't really compare what you have posted with what is at the link. Hopefully it will be useful to you:
http://davidkeaveny.blogspot.com/2011/03/unity-and-log4net.html
I've been trying to achieve the same result of being able to insert correctly configured ILog
instances into a dependency using constructor injection with Unity.
In the end, I wrote my own "log4net" unity extension to do exactly this (in part inspired by a blog post that another answerer, Kenneth Baltrinic, wrote).
This allows you to register the extension once with Unity:
var container = new UnityContainer(); container.AddNewExtension<Log4NetExtension>();
and then have the correct ILog logger instance passed in:
public class MyClass { private readonly ILog logger; public MyClass(ILog logger) { this.logger = logger; } }
The extension can be found here:
https://github.com/roblevine/UnityLoggingExtensions
More info here: http://blog.roblevine.co.uk/net/using-log4net-with-unity/
EDIT this is now available as a NuGet package
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