Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind Interface in Ninject only if it is not already bound?

Is it possible to configure Ninject to not bind a dependency if it is already bound.

E.g.

If we load a module say called Client1 containing:

public class Client1Module:NinjectModule
{
    public override void Load()
    {
         Bind<IService>.To<FancyService>()
    }
}

Then we load a module called Base containing

public class BaseModule:NinjectModule
{
    public override void Load()
    {
          Bind<IService>.To<BasicService>()
    }
}

We would like to ensure that BasicService isn't bound and the system always uses FancyService. We won't know at design time whether FancyService exists. Client1 module is loaded if it is located.

I don't really want a bunch of repeitive boiler plate code around every injection etc. As there are 50-60 dependencies that all could be changed in Client modules.

Any ideas?

like image 722
GraemeMiller Avatar asked Sep 07 '12 10:09

GraemeMiller


2 Answers

You have to make sure BaseModule is loaded after Client1Module:

   public class BaseModule: NinjectModule
    {
        public override void Load()
        {
            if (!Kernel.GetBindings(typeof(IService)).Any())
            {
                Bind<IService>().To<BasicService>();
            }
        }
    }
like image 54
armen.shimoon Avatar answered Oct 23 '22 23:10

armen.shimoon


If I assume I load the base Module first and then load the Client Module after I think I can just use

Rebind<IService>.To<FancyService>()

It seems to work

like image 38
GraemeMiller Avatar answered Oct 23 '22 23:10

GraemeMiller