Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override existing binding without removing all conditional such?

Tags:

c#

.net

ninject

The challenge I am facing with Ninject currently is that when I use Rebind<>() it removes all bindings, even those that are conditional. Let me give you a silly example below. Basically what I find undesired behaviour in my case is that when Rebind is called it will remove the conditional WhenInjectedInto<T> binding instead of just overwriting the non-conditional Bind<T>. In the sample below the contract Contract.Assert(cat is Wild); in the ctor will fail after the Rebind.

Is there a way to do what I want - being the ability to keep already injected conditional bindings and overwrite only the non-conditional one?

P.S: In reality I am trying to do some interesting things with DataContext scopes depending on where they are injected (in a request or in an async command)

void Main()
{
    StandardKernel kernel = new StandardKernel();

    kernel.Bind<ICat>().To<Wild>();
    kernel.Bind<ICat>().To<Wild>()
        .WhenInjectedInto<EvilCat>();

    kernel.Rebind<ICat>().To<Domestic>();

    Contract.Assert(kernel.Get<ICat>() is Domestic);
    kernel.Get<EvilCat>();
}

interface ICat {}

class Domestic : ICat {}

class Wild : ICat { }

class EvilCat
{
    public EvilCat(ICat cat) {
        Contract.Assert(cat is Wild);
    }
}
like image 598
Ivan Zlatev Avatar asked Nov 27 '12 17:11

Ivan Zlatev


1 Answers

Try this:

kernel.GetBindings(typeof(ICat)).
            Where(binding => !binding.IsConditional).
            ToList().
            ForEach(
                binding => 
                    kernel.RemoveBinding(binding)
            )

kernel.Bind<ICat>().To<Domestic>();

Of course you can do it without LINQ in a foreach:

var bindings = kernel.GetBindings(typeof(ICat)).ToList();
foreach(var binding in bindings)
{
     if (!binding.IsConditional)
          kernel.RemoveBinding(binding);
}

kernel.Bind<ICat>().To<Domestic>();
like image 195
Lukas Wöhrl Avatar answered Oct 23 '22 03:10

Lukas Wöhrl