ASP.NET Basics: Inject Service into Controller

bradwellsb

Bradley Wells

Posted on April 6, 2020

ASP.NET Basics: Inject Service into Controller

In this tutorial, you will learn how to use C# dependency injection to inject a service into a controller. This is useful if you need to call an action from within a separate controller.

Register Service Class

First, register your service class with the ServiceCollection interface. Open Startup.cs of your project and locate the ConfigureServices method. Depending on how your service is configured, you might register it through the HttpClientFactory.

services.AddHttpClient<ApiService>(client =>
{
    client.BaseAddress = new Uri(Configuration["ApiBase"]);
})

Or you might register as a service with Singleton, Scoped, or Transient lifetime.

services.AddTransient<ApiService>();

Inject into Controller

To inject the service into your controller, use the standard C# dependency injection technique.

[Route("stripe/[controller]")]
public class CustomerWebhook : ControllerBase
{
    private readonly ApiService _apiService;
    public CustomerWebhook(ApiService apiService)
    {
        _apiService = apiService;
    }

    //Add controller actions
}

Invoke Service Method from Controller

Suppose you have a method in your service class that calls an API controller to get a user from the database by the user’s ID.

public async Task<User> GetUserByIdAsync(int id)
{
    var response = await _httpClient.GetAsync($"api/users({id})");
    response.EnsureSuccessStatusCode();
    using var responseContent = await response.Content.ReadAsStreamAsync();
    return await JsonSerializer.DeserializeAsync<User>(responseContent);            
}

The service class’s GetUserByIdAsync() method interacts with the project’s UsersController. You might need this user information from within another controller, AnotherController. If you have injected ApiService as a dependency in AnotherController , you can easily use it to interact with UsersController.

var dbUser = await _apiService.GetUserById(userId);

The Bottom Line

In this tutorial, you learned how to inject a service into a controller. That controller could be an API controller, an MVC controller, or a webhooks receiver. In the next tutorial, we will put this technique into practice as we create a listener controller to respond to webhooks sent by Stripe.

Source

💖 💪 🙅 🚩
bradwellsb
Bradley Wells

Posted on April 6, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related