0

I am trying to register conditionally (based on implementation type) a custom ApiClient using SimpleInjector as can be seen in the following function.

private static void RegisterEndpoint<TServiceType>(
    string param1, string param2, string param3)
{
    var registration =
        Lifestyle.Scoped.CreateRegistration<IMyApiClient<HttpClient>>(
            () => new MyApiClient<HttpClient>(param1, param2, param3),
            container);

    container.RegisterConditional<IMyApiClient<HttpClient>>(
        registration,
        c => c.Consumer.ImplementationType == typeof(TServiceType));
 }

However when loading the asp.net page I get the following error:

Calling the PredicateContext.Consumer property for a conditional registration that is requested directly from the container is not supported. IMyApiClient<HttpClient> is requested directly from the container opposed to it being injected into another class, which causes this exception. If IMyApiClient<HttpClient> needs to be requested directly (e.g. by calling container.GetInstance<IMyApiClient<HttpClient>>()), check the PredicateContext.HasConsumer property inside the predicate to determine whether PredicateContext.Consumer can be called, e.g. container.RegisterConditional(typeof(IMyApiClient<>), typeof(IMyApiClient<>), c => c.HasConsumer ? c.Consumer.ImplementationType == typeof(MyConsumer) : true). Only call PredicateContext.Consumer when PredicateContext.HasConsumer returns true.

IMyApiClient<HttpClient> is not requested directly from the container anywhere in the code. It's only being injected in a few constructors.

3
  • Can you demonstrate this problem by providing us with a Minimal, Reproducible Example? And please post the complete stack trace.
    – Steven
    Jul 21, 2022 at 19:52
  • Hi doorman. As it currently stands, your question unfortunately has too little information to be answered. Please update your question with the suggestions provided in my previous comment and post a comment when you did that. Using this information I'll likely be able to help you and answer your question.
    – Steven
    Jul 22, 2022 at 14:25
  • Hi @Steven thanks for reaching out. I changed the implementation a bit so now I can simply use RegisterInstance instead.
    – doorman
    Jul 22, 2022 at 22:42

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.