When implementing DI, both Mark Seemann, and Misko Hevery say that constructors should be simple, and should only receive dependencies. They should not do anything else. (here and here)
However, often I would like to subscribe to events of the passed in dependencies, but if I do this in the constructor, then the constructor does more than receiving its dependencies, and if I don't, then the object is not fully initialized.
Would it be correct, then, to instantiate those objects which need to subscribe to events in the composition root, hook up their events, and then inject those instantiated objects?
For example:
// Composition root
Panel panel = new Panel();
Button button = new Button();
panel.OnButtonClick += button.Click;
Register<Panel>().AsSingle(panel);
Register<Button>().AsSingle(button);
// Panel Class
private Button _button;
public Panel(Button button)
{
_button = button;
}
void OnButtonClick()
{
// handle button click
}
as opposed to:
//composition root
Register<Panel>().AsSingle(panel);
Register<Button>().AsSingle(button);
// Panel Class
private Button _button;
public Panel(Button button)
{
_button = button;
OnButtonClick += button.Click
}
void OnButtonClick()
{
// handle button click
}