-
-
Save vendettamit/ed1cdcaeedf7bc03f59b to your computer and use it in GitHub Desktop.
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
public class LogInjectionModule : Module { | |
protected override void AttachToComponentRegistration(IComponentRegistry registry, | |
IComponentRegistration registration) { | |
registration.Preparing += OnComponentPreparing; | |
var implementationType = registration.Activator.LimitType; | |
var injectors = BuildInjectors(implementationType).ToArray(); | |
if (!injectors.Any()) { | |
return; | |
} | |
registration.Activated += (s, e) => { | |
foreach (var injector in injectors) { | |
injector(e.Context, e.Instance); | |
} | |
}; | |
} | |
private static void OnComponentPreparing(object sender, PreparingEventArgs e) { | |
var t = e.Component.Activator.LimitType; | |
e.Parameters = | |
e.Parameters.Union(new[] | |
{new ResolvedParameter((p, i) => p.ParameterType == typeof (ILog), (p, i) => LogManager.GetLogger(t))}); | |
} | |
private static IEnumerable<Action<IComponentContext, object>> BuildInjectors(Type componentType) { | |
var properties = | |
componentType.GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance) | |
.Where(p => p.PropertyType == typeof(ILog) && !p.GetIndexParameters().Any()) | |
.Where(p => | |
{ | |
var accessors = p.GetAccessors(false); | |
return accessors.Length != -1 || accessors[0].ReturnType == typeof(void); | |
}); | |
foreach (var propertyInfo in properties) | |
{ | |
var propInfo = propertyInfo; | |
yield return (context, instance) => propInfo.SetValue(instance, LogManager.GetLogger(componentType), null); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment