Conditional Binding in WebApi2 Controller Method

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 this. My method Get()must be executed, and it does not depend on the value IMyFooService, so I don’t care whether it will be introduced or not when requested Get().

Question:

Is there a way to selectively bind interfaces only when calling certain api methods? Through the use of 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 mine NinjectWebCommon.cs:

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

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

+4
2

, , - Lazy<T>, - :

, .

Lazy<T> Ninject.Extensions.Factory ( . Wiki Lazy<T>). nuget, Lazy<T>.

:

public class FooController : ApiController {

    public Lazy<IMyFooService> fooService;

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

    public JsonResult Get() {}

    public async Task<JsonResult> Post([FromBody] IList foos) {
        var didMyFoo = this.fooService.Value.DoTheFoo();
    }
}

, .Value Lazy<T>. .

+4

. . IsRouteValueDefined ( , - IsRoutePoitingTo) - ( , WebApi, , , ):

public static bool IsRouteValueDefined(string controller, string action)
{
    var mvcHanlder = (MvcHandler)HttpContext.Current.Handler;
    var routeValues = mvcHanlder.RequestContext.RouteData.Values;
    var containsRouteKey = routeValues.ContainsKey(routeKey);
    if (routeValue == null)
        return containsRouteKey;

    return containsRouteKey &&
           routeValues["controller"].ToString().Equals(controller, StringComparison.InvariantCultureIgnoreCase) &&
           routeValues["action"].ToString().Equals(action, StringComparison.InvariantCultureIgnoreCase);
}

:

kernel.Bind<IMyFooService>()
      .To<MyConcreteService>()
      .When(x=> IsRouteValueDefined("foo", "get"));

, "", ApiController, http://website.com/foo/, , string.Empty "". . ( ), .

0

Source: https://habr.com/ru/post/1681473/


All Articles