Skip to content

Instantly share code, notes, and snippets.

@vendettamit
Forked from jayharris/LogInjectionModule
Last active August 29, 2015 14:20
Show Gist options
  • Save vendettamit/ed1cdcaeedf7bc03f59b to your computer and use it in GitHub Desktop.
Save vendettamit/ed1cdcaeedf7bc03f59b to your computer and use it in GitHub Desktop.
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