Attribute to choose preferred registration of multiple type registration on constructor parameter #40055
Unanswered
flipthetrain
asked this question in
General
Replies: 1 comment
-
This introduces coupling between the service consuming the interface and the registration of that interface implementation. Maybe ServiceDescriptor could be extended to support an optional TargetService type. That would be used like how you suggest but it would only pollute the registration APIs not the consumer of the interface. services.AddSingleton<IFoo, Foo1, TargetService1>();
services.AddSingleton<IFoo, Foo2, TargetService2>(); Any changes to the core interface require changes to all other containers that implement the DI contract. That's one of the reasons we haven't done anything in this space. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
One thing that I think .Net Core DI/IOC does weakly, is how to manage multiple implementations of the same interface.
I would really like to be able to do something like this
services.AddTransient<IMyInterface,Impl_1>()
services.AddTransient<IMyInterface.Impl_2>()
services.AddTransient<IMyInterface.Impl_3>()
services.AddTransient<MyClass.>()
One option is on my class constructor to use an Attribute to define the preferred registered type
[PreferredType(IMyInterface,typeof(Impl_1))]
[PreferredType(IMyInterface,typeof(Impl_3),2)]
[PreferredType(IMyInterface,typeof(Impl_2),3)]
public class MyClass
public MyClass(IMyInterface myInterface)
Another option is to pass the preferred type in the registration of MyClass as such
services.AddTransient<MyClass.>(Dictionary<Type,Type> PreferredTypes)
services.AddTransient<MyClass.>(Dictionary<Type,OrderList> PreferredTypes)
Then when I call
serviceProvider.GetService()
this seems to me to be a lot less cumbersome than creating an implementation factory and it gives the benefit of prioritizing implementations.
I'm just looking for interest or if this is a commonly desired feature or if it's not even worth the time to develop.
thanks...
Beta Was this translation helpful? Give feedback.
All reactions