ASP.NET 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.


Inject into Controller

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

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})");
	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.

Was this article helpful? Share it with your friends:

Share on email
Share on facebook
Share on twitter
Share on reddit

1 thought on “ASP.NET Inject Service into Controller”

  1. Hi Brad

    I love ALL your blogs. Very useful and precious.
    I was wondering if you could write a blog how to contact STRIPE server directly from Blazor WASM to send CC info and get token, bypassing sending CC info to ASP server to send to STRIPE.

    Currently STRIPE has a full JS library & SDK with Element UI that allows JS apps to talk directly to Stripe server for secure transaction, but we don’t have that (to the best of my knowledge) a native way from Blazor client to talk to Stripe server. Or is there a way to do so with .Net standard in Blazor client?


Leave a Comment

Looking for more?

You have visited our site before, and we appreciate you!

If you found the tutorials helpful, enter your email address for more free C# tips and tricks.

Can't get enough C#?

Enter your email address for more free C# tutorials and tips.