I have a set of utility classes that I want to inject using Angular's DI system. Is this possible, or should I stick to simple static methods? I like the ability to mock them in my tests. How do I 'register' a plain old TypeScript class in the Angular DI container?
Angular allows non-component TypeScript classes to be registered in the dependency injection container by using the @Injectable decorator and defining them in a provider array, enabling them to be injected into constructors for enhanced testability.
1 answer
Yes, you can absolutely register plain TypeScript classes in Angular's dependency injection container, and doing so is actually a prerequisite for maintaining proper testability and loose coupling in any system under rigorous verification.
You simply decorate your utility class with @Injectable({ providedIn: 'root' }) or include it in the providers array of an NgModule or component, which effectively integrates it into the framework's lifecycle.

