Tell if Ninject convention bind failed

113 Views Asked by At

I am using Ninject.Extensions.Conventions to add bindings dynamically. The .dll names to load are stored in configuration. If the configuration is incorrect and the .dll can not be loaded it would be good to know about that. Currently any failure to load a .dll is not bubbled up. For example, if I try to load a potato there is no error I can catch:

foreach (var customModule in customModuleConfigs)
{
    KeyValuePair<string, KVP> module = customModule;

    _kernel.Bind(scanner => scanner
        .From(module.Value.Value)
        .SelectAllClasses().InheritedFrom<ICamModule>()
        .BindAllInterfaces());

    // I need to know this failed
    _kernel.Bind(scanner => scanner
        .From("potato")
        .SelectAllClasses().InheritedFrom<ICamModule>()
        .BindAllInterfaces());
}

Is there a way to know I have a bad configuration? In the IntelliTrace window I see an exception thrown but caught before it bubbles up.

2

There are 2 best solutions below

1
On BEST ANSWER

You'll need to do the loading of the Assembly yourself, then you can control whether there is an exception thrown. Use the

From(params Assembly[] assemblies) overload.

Load the assembly by either using Assembly.LoadFrom() or Assembly.Load.

1
On

You could create a wrapper around the AllInterfacesBindingGenerator class and use this to count the generated bindings:

public class CountingInterfaceBindingGenerator : IBindingGenerator
{
    private readonly IBindingGenerator innerBindingGenerator;

    public CountingInterfaceBindingGenerator()
    {
        this.innerBindingGenerator =
            new AllInterfacesBindingGenerator(new BindableTypeSelector(), new SingleConfigurationBindingCreator());
    }

    public int Count { get; private set; }

    public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
    {
        this.Count++;

        return this.innerBindingGenerator.CreateBindings(type, bindingRoot);
    }
}

Usage:

var kernel = new StandardKernel();
var bindingGenerator = new CountingInterfaceBindingGenerator();

kernel.Bind(b =>
{
    b.From("potato")
        .SelectAllClasses()
        .InheritedFrom<ICamModule>()
        .BindWith(bindingGenerator);
});

if (bindingGenerator.Count == 0)
    // whatever

This is probably longer than your current code, but it would allow further customization of the bindings that have been created.