Friday, April 28, 2023

How to Implement Dependency Injection in .NET Web API project

Here is an example of how you could implement dependency injection in a .NET Web API project.

First, create an interface for the service that you want to inject:
  1. public interface IMyService
  2. {
  3. string GetMessage();
  4. }
Next, create a class that implements the interface:
  1. public class MyService : IMyService
  2. {
  3. public string GetMessage()
  4. {
  5. return "Hello, world!";
  6. }
  7. }
In your Web API project, register the service with the dependency injection container (in this example, we'll use the built-in ASP.NET Core DI container):
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. // Register the service with the DI container
  4. services.AddScoped<IMyService, MyService>();
  5.  
  6. // Other configuration code...
  7. }
Finally, inject the service into a controller or other component that needs it:
  1. public class MyController : ControllerBase
  2. {
  3. private readonly IMyService _myService;
  4.  
  5. public MyController(IMyService myService)
  6. {
  7. _myService = myService;
  8. }
  9.  
  10. [HttpGet]
  11. public IActionResult Get()
  12. {
  13. var message = _myService.GetMessage();
  14. return Ok(message);
  15. }
  16. }
In this example, we've registered `MyService` as an implementation of the `IMyService` interface using the `AddScoped` method, which means that a new instance of `MyService` will be created for each HTTP request.

We then inject `IMyService` into our `MyController` using constructor injection, which allows us to use the `GetMessage` method of `MyService` in the `Get` method of our controller.

No comments:

Post a Comment