NInject contextual binding When method is called too many times

460 Views Asked by At
interface IWarrior
{
}

class Samurai : IWarrior
{
}

public class Program
{
    public static void Main(string[] args)
    {
        var kernel = new StandardKernel();

        kernel.Bind<IWarrior>().To<Samurai>().When(i =>
        {
            Console.WriteLine("test");
            return true;
        });

        IWarrior warrior = kernel.Get<IWarrior>();
    }
}

Here is very simple scenario, I'm creating dummy interface + implementation and bind them using NInject's Contextual Binding and When method which return true, and it also output "test" message to the console when called. I thought When() would be called only once per Get<>() expected it to output "test" only once, But magically(or Not?^_^) it outputs 3 times "test",

test
test
test

which means that When() is called 3 times per one Get<>() request(I added another implementation of IWarrior and bound it, then output count was 6(3 per binding)).

Why does it happen? We're going to put some non-trivial(and time consuming too) checks per binding, but calling it three times instead of one would be an issue.

1

There are 1 best solutions below

0
On BEST ANSWER

For a single activation, Ninject will evaluate if it can resolve your request by using the delegate provided in the When. And due to Ninject's internal implementation, it may call upon that multiple times. The source for this is the Ninject source code available on github.

It has no means of knowing the type of conditional or if the logic is time-consuming.

And as a note: This is one of the reasons why Ninject container is much slower per activation request than others. Precisely because it's support for advanced contextual/conditional bindings, where each activation request must be evaluated given its context (and not be cached).