Can I Use Ninject To Bind A Boolean Value To A Named Constructor Value

StackOverflow https://stackoverflow.com/questions/22512353

  •  17-06-2023
  •  | 
  •  

Pregunta

I have a constructor such as:

public AnalyticsController(ClassA classA, ClassB classB, bool isLiveEnvironment)
{
   ...
}

isLiveEnvironment is determined using a call to an existing static class such as:

MultiTenancyDetection.GetInstance().IsLive();

I would like to be able to make this call outside of the controller and inject the result into isLiveEnvironment. Is this possible? I can not see how this can be done.

¿Fue útil?

Solución

You can accomplish this using WithConstructorArgument and using a callback:

kernel.Bind<AnalyticsController>()
      .ToSelf()
      .WithConstructorArgument("isLiveEnvironment", ctx => MultiTenancyDetection.GetInstance().IsLive() );

Otros consejos

You can even achieve this more generally (but i would not really recommend binding such a generic type for such a specific use case):

IBindingRoot.Bind<bool>().ToMethod(x => MultiTenancyDetection.GetInstance().IsLive())
    .When(x => x.Target.Name == "isLiveEnvironment");

Alternatively, if you need the same configuration value in several / a lot of classes, create an interface for it:

public interface IEnvironment
{
    bool IsLive { get; }
}

internal class Environment : IEnvironment
{
    public bool IsLive
    {
        get
        {
            return MultiTenancyDetection.GetInstance().IsLive();
        }
    }
}

IBindingRoot.Bind<IEnvironment>().To<Environment>();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top