Created
August 18, 2016 08:06
-
-
Save petermorlion/9e5ed7f86a48f9a242a7188858b2acaf to your computer and use it in GitHub Desktop.
Autofac LoggingModule
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <remarks> | |
/// Found in the Autofac documentation: http://docs.autofac.org/en/latest/examples/log4net.html | |
/// </remarks> | |
public class LoggingModule : Autofac.Module | |
{ | |
private static void InjectLoggerProperties(object instance) | |
{ | |
var instanceType = instance.GetType(); | |
// Get all the injectable properties to set. | |
// If you wanted to ensure the properties were only UNSET properties, | |
// here's where you'd do it. | |
var properties = instanceType | |
.GetProperties(BindingFlags.Public | BindingFlags.Instance) | |
.Where(p => p.PropertyType == typeof(ILog) && p.CanWrite && p.GetIndexParameters().Length == 0); | |
// Set the properties located. | |
foreach (var propToSet in properties) | |
{ | |
propToSet.SetValue(instance, LogManager.GetLogger(instanceType), null); | |
} | |
} | |
private static void OnComponentPreparing(object sender, PreparingEventArgs e) | |
{ | |
e.Parameters = e.Parameters.Union( | |
new[] | |
{ | |
new ResolvedParameter( | |
(p, i) => p.ParameterType == typeof(ILog), | |
(p, i) => LogManager.GetLogger(p.Member.DeclaringType) | |
), | |
}); | |
} | |
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) | |
{ | |
// Handle constructor parameters. | |
registration.Preparing += OnComponentPreparing; | |
// Handle properties. | |
registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment