Question

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.

Was it helpful?

Solution

You can accomplish this using WithConstructorArgument and using a callback:

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

OTHER TIPS

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>();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top