0

Hod do you inject some class based on request host value? I installed Ninject MVC3 lib via Nuget. I'm looking for something like this:

private static void RegisterServices(IKernel kernel)
{
    var host = get host from request;

    if (host.StartstWith("x."))
    {
        kernel.Bind<IMyInterface>().To<XImplementation>().InRequestScope();
    }
    else if (host.StartstWith("y."))
    {
        kernel.Bind<IMyInterface>().To<YImplementation>().InRequestScope();
    }
}   

Edit: just found this answer.. is there any other way than factory? Like the one in my "pseudo" example above?

Solution:

private static void RegisterServices(IKernel kernel)
{
    var host = HttpContext.Current.Request.Headers["host"].ToLower();

    kernel.Bind<IMyInterface>().To<XImplementation>().When(ctx => host.StartsWith("x.")).InRequestScope();
    kernel.Bind<IMyInterface>().To<YImplementation>().When(ctx => host.StartsWith("y.")).InRequestScope();
}   
Community
  • 1
  • 1
redman
  • 2,115
  • 5
  • 32
  • 59
  • No way should you be registering per-request. Search Mark Seemann RRR pattern – Ruben Bartelink Jan 15 '12 at 00:32
  • You can use ToMethod, ToProvider or build a Factory of your own if the conditional constructs are insufficient. In general, the conditional approach should be your first port of call - see @Simon Halsey's answer – Ruben Bartelink Jan 15 '12 at 00:33
  • @RubenBartelink if I remove .InRequestScope(), what else is wrong with using To in combination with When like in my example? Is using factory a better whey? If it is why is so? – redman Jan 15 '12 at 11:17
  • The scoping is orthogonal to any of my points. My point is that you shouldnt be using anything out of `HttpContext` in your Registration phase. No problems with using To with When. (Also your code on refelction doesnt make sense as you're calculating the host once and then registering 2 bindings, ponly one of which can ever be used). Whether to use two conditional bindings or a factory with an **if** in it depends on your contect - neither is dramatically better in general - it's more whether it's an app-logicy concern or a DI-type-thing concern. – Ruben Bartelink Jan 15 '12 at 21:43

2 Answers2

2

Does this help?

https://github.com/ninject/ninject/wiki/Contextual-Binding

There is mention of a similar example to what you're doing but it references v1 not v2

https://github.com/ninject/ninject/wiki/Conventions-Based-Binding

Simon Halsey
  • 5,459
  • 1
  • 21
  • 32
1

Try this way.

Bind<IMyInterface>().To<XImplementation>().When(ctx => host.StartstWith("x.")).InRequestScope();
Bind<IMyInterface>().To<YImplementation>().When(ctx => host.StartstWith("y.")).InRequestScope();
wnascimento
  • 1,949
  • 1
  • 19
  • 16
  • Careful, you've propagated the error in the question in using `host` which is effectively a constant for the life of the binding. – Ruben Bartelink Jan 15 '12 at 23:22