Why do I see dependency injection so often in the context of hosted services?

60 Views Asked by At

I'm new to C# (and programming in general) and I've recently learned about how background tasks can be implemented using hosted services (e.g. schedule a task to fire at regular intervals). I've been reading up about associated concepts, like long-running background services, the worker service template and the Windows Services that you can see in Task Manager.

However, what I'm struggling to understand is why dependency injection (and DI containers) constantly gets mentioned in the documentation. (See this example about how the generic host created by HostBuilder manages DI, I think. Or, here, which says that worker services make you 'DI ready'.) I've recently learned what DI is (I think), in that it allows us to decouple relationships between objects, and that containers handle instantiation where there is a complex dependency hierarchy. But what I don't get is why they're so integral to service hosting that I'm constantly reading about DI. Is that because the background tasks themselves are object that get injected? Or are these background tasks represented by objects that all have a multitude of dependencies? Or is it something else?

0

There are 0 best solutions below