I see met开发者_运维百科hods for enumerating lists of bindings for a given service (type), but nowhere do I find a method returning a list of everything that's been bound in my loaded modules.
I'm looking for something like Kernel::IEnumerable<IBinding> GetAllRegisteredBindings()
Does this exist? If not, might I be able to build an extension that could do it? I'd need to be able to get to the bindings w/out a service type...
I looked through the code and didn't see a way to request all of the bindings. If you're comfortable with modifying it and using the modified code, here's what you can do:
to IKernel.cs, add:
/// <summary>
/// Gets all registered bindings
/// </summary>
IEnumerable<IBinding> GetBindings();
to KernelBase.cs, add:
/// <summary>
/// Gets all registered bindings
/// </summary>
public virtual IEnumerable<IBinding> GetBindings()
{
return _bindings.SelectMany( kvp => kvp.Value );
}
and recompile.
to use:
var bindings = Kernel.GetBindings();
bindings.ForEach( b => logger.DebugFormat( "Binding: {0} -> {1}", b.Service, b.Target ) );
While @dave thieben isnt far wrong, it would appear that your route in without requiring forkage may be to register a custom IBindingResolver
Component in the Kernel and then concoct an IRequest
that it will recognise, possibly via ResolutionExtensions.GetAll()
(in general, most will require you to specify a service
(though none Ensure.NotNull
on it, some go party on it assuming NotNull
).
But you forgot to say why you want it.
Thus I recommend:
- saying what you want
- asking on the ninject mailing list, including the answer to #1 - this is no beginner question!
I was able to use reflection to do this:
KernelBase baseKernel = (KernelBase)Kernel;
// _commandCollection is an instance, private member
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
// Retrieve a FieldInfo instance corresponding to the field
FieldInfo field = typeof(KernelBase).GetField("bindings", flags);
Multimap<Type, IBinding> bindingsMap = (Multimap<Type, IBinding>)field.GetValue(baseKernel);
bindingsMap.SelectMany(x => x.Value).ToList().ForEach(x => log.DebugFormat("Binding: {0} -> {1}", x.Service, x.Target));
精彩评论