I have the following scenario in a .net core C# application:
Service A -> Subject<Foo> -> Service B
Service C -> Subject<Foo> -> Service D
The two instances of Subject<Foo>
have different semantics, so they need to be different instances. Lets assume the first subject delivers "awesome" Foo
s, the second delivers "great" Foo
s.
Service A has a dependency to Subject<Foo>
as well as Service B. Now, I'd like to use the dependency injection that ships with dotnet core to add two instances of the Subject<Foo>
to the container so that all services can be constructed with the subjects they depend on (A and B depend on the first instance, C and D on the second).
My first idea was to create derived interfaces IFooFirstSubject : ISubject<Foo>
and IFooSecondSubject : ISubject<Foo>
:
services.AddSingleton<IFooFirstSubject>( HOW TO GET A FooFirstSubject Instance?! );
services.AddSingleton<IFooSecondSubject>( HOW TO GET A FooSecondSubject Instance?! );
However, now I need a concrete Subject implementation that implements the IFooFirstSubject
interface. One idea was to subclass Subject
and implement the marker interface but Subject
is a sealed class. I currently see three approaches and I'm not happy with either:
1) Instead of making A und B depended on the subject, create a SubjectRegister
concrete class, from which A,B,C,D can query the subject they want like subjectRegister.FooFirstSubject
. Having the register in between seems like a smell to me.
2) Use the adapter pattern to solve the sealed class issue. FooFirstSubject
could then implement IFooFirstSubject
and use (not derive from) a Subject
. That seems like a whole lot of work if I have many subjects between my services.
3) There might be a way to add the marker interface using reflection. Which also feels like I am doing something that is not meant to be done.
In essense: Is there another way (maybe I am even using the wrong class with Subject
here?) to achieve what I am trying to do?
Edit: I created a lengthy explanation on the why and what i am trying to accomplish here (due to the many comments, thanks for them!): https://gist.github.com/anonymous/e933846c2c8e213128a49a2a6f8f7154