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);
}
}
Try this:
Of course you can do it without LINQ in a foreach: