Conditional binding in WebApi2 controller method

Viewed 346

I am using Ninject with the following packages:

  • Ninject
  • Ninject.MVC5
  • Ninject.Web.Common (and Common.WebHost)
  • Ninject.Web.WebApi (and WebApi.WebHost)

I have a WebApi2 Controller that looks like the below. My Get() method must be performant and it doesn't depend on the value of IMyFooService, thus I don't care if it gets injected or not when Get() is requested.

Question:

Is there a way for me to selectively bind interfaces only if certain api methods are called? Whether through using attributes or...?

public class FooController : ApiController {

    public IMyFooService fooService;

    public FooController(IMyFooService fooService) {
        this.fooService = fooService;
    }

    [NonDependent] // Don't really care about the value of fooService
    public JsonResult Get() {}

    [Dependent] // Must have valid dependency injection
    public async Task<JsonResult> Post([FromBody] IList foos) {
        var didMyFoo = this.fooService.DoTheFoo();
    }
}

Here is my NinjectWebCommon.cs:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IMyFooService>().To<MyConcreteService>().InRequestScope();
}

I noticed that To<T>() has many .When() options. Perhaps I can make use of this to say .When(/* Controller = Foo, Action = Post */).

2 Answers
Related