Question

I'm trying to inject a parameter that is evaluated lazily:

private readonly Lazy<IIdentifier> _userIdentifier;

public DocumentController(Lazy<IIdentifier> userIdentifier)
{
    _userIdentifier = userIdentifier;
}

userIdentifier isn't expensive to create, but this is a WebApi application, and userIdentifier is extracted from another object that depends on HTTPContext, which is null at App_Start time. Having to specify Lazy in the controller constructor seems like a code smell since the controller shouldn't need to know or care that this parameter needs special handling at composition time.

It's being injected like this:

kernel.Bind<IIdentifier>()
      .ToMethod(x => kernel.Get<IMinimalSecurityToken>().UserID);

I don't think I can use the Ninject Factory extension in this case, since it isn't as simple as newing up an instance of the object. I'd rather not write a factory just to handle this case, although I suppose that would be preferable to sticking the Lazy into the controller, so I'm hoping that there is some way to use the automatic factory from Ninject that I'm just not thinking of.

Was it helpful?

Solution

IF you don't want to use a factory and I agree a factory doesn't quite suite the use case here. Instead you can use a provider to serve you a token.

public class MyIdentityProvider : Provider<IIdentifier>
{
    ...
}

kernel.Bind<IIdentifier>().ToProvider<MyIdentityProvider>();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top