Skip to content

Instantly share code, notes, and snippets.

@crmckenzie
Last active December 15, 2015 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crmckenzie/5338433 to your computer and use it in GitHub Desktop.
Save crmckenzie/5338433 to your computer and use it in GitHub Desktop.
Get registered bindings from Ninject.
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