DI registration of multiple abstract classes

Viewed 58

Consider these classes:

public interface IFoo<TA, TB> where TA : IFoo2<TB> where TB: class {}

public interface IFoo2<T> where T : class {}

public class Foo2 : IFoo2<string> {}

public abstract class AbstractFoo<TA, TB> : IFoo<TA, TB> where TA : class, IFoo2<TB> where TB : class {}

public class MyClass1 : AbstractFoo<Foo2, string> {}

public class MyClass2 : AbstractFoo<Foo2, string> {}

I inject both implementations into the DI container, and I need to select one them based on a condition:

services.AddScoped<MyClass1>();
services.AddScoped<MyClass2>();
services.AddScoped<Func<string, IFoo<IFoo2<string>, string>>>(serviceProvider => key => 
    {
        return key switch
        {
            "MyClass1" => serviceProvider.GetService<MyClass1>(),
            "MyClass2" => serviceProvider.GetService<MyClass2>(),
            _ => throw new ArgumentOutOfRangeException(nameof(key), key, null)
        };
    }
);

That won't work though, because the implementations cannot implicitly be converted to IFoo<IFoo2<string>, string>.

How can I modify the registrations in order to compile?

0 Answers
Related