Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection - Subscribing to events in the composition root instead of the constructor

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
}
like image 850
jmrah Avatar asked Nov 27 '25 00:11

jmrah


1 Answers

Yes, wiring up the events in the composition root would be the correct approach here.

like image 182
Darin Dimitrov Avatar answered Nov 28 '25 14:11

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!