DEV Community

Bradley Wells
Bradley Wells

Posted on • Originally published at wellsb.com on

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

Top comments (1)

Collapse
 
zakwillis profile image
zakwillis

Hi Bradley. Hope you are doing well. Am trying to understand why we would call a Web service/api controller method from within the same Web project when it would make far more sense to call the underlying library/service? Would it not involve going over http/s for code that existed in the same library?
Probably need to reread this to understand it.