Last active
December 15, 2015 23:09
-
-
Save crmckenzie/5338433 to your computer and use it in GitHub Desktop.
Get registered bindings from Ninject.
This file contains hidden or 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 InjectionBinding | |
{ | |
public Type RegistrationKey { get; set; } | |
public IList<object> Implementations { get; set; } | |
public Type[] GetImplementationTypes() | |
{ | |
return Implementations.Select(row => row.GetType()).ToArray(); | |
} | |
} | |
// relies on the implementation of KernelBase since | |
// Ninject does not allow you to query bindings via | |
// its api. | |
public static class NinjectExtensions | |
{ | |
public static IEnumerable<InjectionBinding> GetImplementations(this KernelBase self, Func<Type, bool> criteria = null ) | |
{ | |
if (criteria == null) | |
criteria = type => true; | |
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; | |
// Retrieve a FieldInfo instance corresponding to the field | |
var field = typeof(KernelBase).GetField("bindings", flags); | |
var bindingsMap = (Multimap<Type, IBinding>)field.GetValue(self); | |
var allBindings = bindingsMap.Keys.SelectMany(key => bindingsMap[key]).ToList(); | |
var allBindingsMatchingCriteria = allBindings | |
.Select(row => row.Service) | |
.Where(row => criteria.Invoke(row)) | |
.ToList() | |
; | |
var keyValues = from instance in allBindingsMatchingCriteria | |
select new InjectionBinding | |
{ | |
RegistrationKey = instance, | |
Implementations = self.GetAll(instance).ToList(), // instance.Implementations.ToList(), | |
}; | |
return keyValues; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment