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:
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.
First, create an interface for the service that you want to inject:
public interface IMyService
{
string GetMessage();
}
Next, create a class that implements the interface:
public class MyService : IMyService
{
public string GetMessage()
{
return "Hello, world!";
}
}
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):
public void ConfigureServices(IServiceCollection services)
{
// Register the service with the DI container
services.AddScoped<IMyService, MyService>();
// Other configuration code...
}
Finally, inject the service into a controller or other component that needs it:
public class MyController : ControllerBase
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
[HttpGet]
public IActionResult Get()
{
var message = _myService.GetMessage();
return Ok(message);
}
}
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