When we use a dependency injection container, ideally we pull only a single-top level object from it (e.g. an instance of Program
) and let the rest of the application be composed automatically by the container.
However, sometimes there are objects which are not a dependency of anything else, yet we want to have them in the object graph. For example, I could have a Notifier
class with a Bazinga
event, and this BazingaConsoleLogger
class:
public class BazingaConsoleLogger
{
private readonly Notifier notifier;
public BazingaConsoleLogger(Notifier notifier)
{
this.notifier = notifier;
this.notifier.Bazinga += HandleBazinga;
}
private void HandleBazinga(object sender, EventArgs args)
{
Console.WriteLine("Bazinga!");
}
}
Because BazingaConsoleLogger
is not a dependency of anything, it will not be created by the dependency injection container. What is the best way to fix this?