Kyle
Kyle

Reputation: 4376

Inject into ToMethod binding

I'm not quite sure how to ask this so I'll just post my code sample and give a brief description of what I'm trying to do. I have the following bindings setup:

kernel.Bind<IAuthenticationService>().To<FormsAuthenticationService>();
kernel.Bind<IAuthenticationService>().To<TokenAuthenticationService>().When(r => HasAncestorOfType<MyWebApiController>(r));

Here's the code for HasAncestorOfType (although I think it's irrelevant here):

private static bool HasAncestorOfType<T>(IRequest request)
{
    if (request.Target == null)
        return false;

    if (request.Target.Member.ReflectedType == typeof(T))
        return true;

    return HasAncestorOfType<T>(request.ParentRequest);
}

These bindings both work as intended (IAuthenticationService is bound to FormsAuthenticationService unless being injected into MyWebApiController in which case it is bound to TokenAuthenticationService). However, I'd like to create a factory binding like this so that ICurrentCompany gets bound to an object created from IAuthentcationService:

kernel.Bind<ICurrentCompany>().ToMethod(x => new Company { CompanyId = x.Kernel.Get<IAuthenticationService>().User.CompanyId});

This doesn't work. IAuthenticationService is always bound to FormsAuthenticationService.

Upvotes: 1

Views: 122

Answers (1)

mipe34
mipe34

Reputation: 5666

The reason why your solution is not working is simply that the request.Target cannot be controller because you are asking (requesting) the instance by "your self" - kernel.Get<>()

I would make Company like this:

public class Company : ICurrentCompany{

     public int CompanyId { get; private set;}

     public class Company(IAuthenticationService authenticationService){
           this.CompanyId = authenticationService.User.CompanyId;
     }
}

and then simply bind:

kernel.Bind<ICurrentCompany>().To<Company>();

then the request.Target will be the controller (at the root of the request hierarchy) and you will get the right service implementation.

Upvotes: 1

Related Questions