Configuring DI in minimal APIs
As standard, ASP.NET offers a way for us to declare that a class we have created can be registered as a service. Converting a class into a service means it can be reused via DI. For example, say you’ve got a piece of logic that calculates overtime pay for any given employee. That logic is the same, but you’ll need it in many other areas of the code base. To avoid writing the same logic again, it’s obvious that you would simply call on the same logic, but as we’ve already discussed, creating a new instance of the class to get to this logic whenever you need it is messy; so, by registering the class as a service, we can cleanly inject it into any other class that needs it.
Moreover, DI allows us to control the life cycle of the service when it is injected. In essence, we can dictate how the dependency is instantiated on each injection and how long it should exist.
There are three built-in lifetime options in ASP.NET:
...