Dependency Injection with .NET Core
Configuring Startup Services and in .NET Core Web APIs
Updated: 03 September 2023
You can think of a service simply as a reusable class instance that can be reused in different controllers. This can be injected via dependency injection where it is needed
Define a Service
To create a new service, you will first need to define a class
that provides the relevant functionality. We can define a simple class for a service as follows:
Add Service
You can the define this as a service in your startup.cs
file’s ConfigureServices
method with the services<T>.AddScoped
function to create a service that can be used by your controllers
Additionally if you would like your service to be able to make use of other services, or do any more complex things, you can access the different parts of the lambda, such as reading from the application config the Name
value
Using the same pattern as above, we can define an SMTP Client with preconfigured information with the following:
The service can then be used by a controller by including a reference based on the service type in the controller’s constructor and its functionality can be used by the controller like with the example below:
Note that the MyCat
service is injected into our controller simply by us defining it in the constructor as a dependency
Different ConnectedServices by Environment
Using the above approach combined with the Visual Studio Connected Services / svcutil
functionality you can set up a different service instance based on your environment configuration with something like this: