Reputation: 321
Suppose I have two services(A and B) both registered as ISomeService. Also suppose I will be needing classes in the future which will need one of these services. But I don't know the class names yet. All I know is they are implementing a given interface or abstract class(All classes implementing a given interface need the same instance of ISomeService). How can I make sure this resolution happens?
Here is a related question where the name of the class which uses the resolved service is known. But in my case the name of the class name CustomerRepository is not known ahead. Only the name of interface(like IUserRepository or IFunctionRepository) or abstract class is known. In other words I just know that SomeRepository: IUserRepository and that IUserRepository types need A. I have to allow user to write more classes implementing IUserRepository.
Here is a better way to put the question. I need all IFunctionRepository constructors to get A(where A:ISomeService) and all IUserRepository constructors to get B(where B:ISomeService)
Upvotes: 1
Views: 992
Reputation: 33920
The question you should be asking yourself is: how can the container know when to use which implementation? Without additional information, the container cannot know this.
And also, with several implementations of ISomeService
, should you require that clients always work with multiple instances?
Usually I would think that services like IUserRepository
only have one implementation at any one time. Sure, you could rip out one implementation and use another, but client classes will only require one instance, not several.
If it is really the case that your container will contain several implementations of the same interface, it should make sense for client classes to accept multiple instances, or at least have some metadata to know which implementation to use.
For clients to accept multiple instances with Autofac is as simple as taking a dependency on IEnumerable<ISomeService>
and the container will hand over all instances. If client classes should make some intelligent decision on which instance to use, you should augment the registrations with metadata. The question you relate to uses some sort of metadata in the form of the classes themselves. A better way is perhaps to use a more decoupled form of metadata. A discussion on how this is implemented in Autofac can be found here.
Upvotes: 2