I have a service that needs to make a callback. Basically, it is an event that is expected to be handled in exactly one place, and that is too important to be optional.
The obvious approach seems to be to inject an Action. In the context of dependency injection, is it considered good (or acceptable) practice to do so?
I'm also eager to hear why (not), or what alternatives you would consider.
One particular problem that comes to mind is in the following scenario:
Parent's constructor takes anIChild.Child's constructor takes anAction, the callback.Parenthas the method that is to receive the callback.- To instantiate the
Child, we need theParent's method, and thus theParentinstance. But to create that, we first need theChildinstance. Problem.
One solution I can think of is to inject an IChildFactory instead. Parent's constructor can then use that factory to create the Child instance. At this point, Parent exists, and thus it can pass its callback method to the factory.
This solution seems to get the job done, but I'm curious about alternatives.
ParentneedsChild, butChildneedsParent(which implements the interface you mention). How would you tackle this?Parent"receives the method" ? I don't understand that part..Childwants to call some log method, andParentwants to dictate how logging is done. This would require us to passParent'sLog()method (orParentitself) toChild's constructor, thus creating the circular dependency.