Read this post on Medium as well
This How-To
describes how to inject dependency to HttpClient
you generated for PetStore API with OpenAPI (Swagger) Connected Service to ASP.NET Core
application. To achieve this please follow the the steps below:
The sample code is available in Samples.AspNetCoreMvc.ClientInjectedToStartup.
- Generate
C#
client class for PetStore API in yourASP.NET Core
MVC
web application using OpenAPI (Swagger) Connected Service. See Getting Started section to install and run thisVisual Studio
extension. - Add new file
PetStoreClient.cs
and make sure the class is marked aspartial
and has the same name and namespace as generatedpublic partial class Client
inPetStoreClient.Generated.cs
. Also define the interfaceIPetStoreClient
. The idea behind using the interfaceIPetStoreClient
is to separate the methods you see where your client is used from what you don't want to expose. In this sample we just expose the method to retrieve the number of pets sold by the store. So we define the methodGetSoldPetsCount
, which internally uses generated method for GET pet/findPetsByStatus endpoint. That is how it might look like:
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Samples.AspNetCoreMvc.ClientInjectedToStartup.PetStore
{
/// <summary>This partial class allows to wrap and extend the generated client logic if you need that.</summary>
public partial class Client : IPetStoreClient
{
// Note: let's implement the interface methods we want to expose
public async Task<int> GetSoldPetsCountAsync()
{
ICollection<Pet> soldPets = await this.FindPetsByStatusAsync(new[] { Anonymous.Sold });
return soldPets.Count;
}
}
/// <summary>Interface defines what we want to expose in our appliction via dependency injection.</summary>
public interface IPetStoreClient
{
/// <summary>Returns number of all sold pets in the store.</summary>
Task<int> GetSoldPetsCountAsync();
// NOTE: you can also define here methods from generated Client partial class to expose them from interface.
}
}
- Now let's use
HttpClientFactory
to inject theIPetStoreClient
. Go toStartup.cs
and add this toConfigureServices(IServiceCollection services)
:
public void ConfigureServices(IServiceCollection services)
{
...
// Inject generated PetStore client via using HttpClientFactory to implement resilient HTTP requests.
services.AddHttpClient<IPetStoreClient, Client>((provider, client) =>
{
client.BaseAddress = new System.Uri("https://petstore.swagger.io/v2/");
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
- In
Index
action inHomeControler.cs
let's injectIPetStoreClient
and pass the number of sold pets to theView
:
public class HomeController : Controller
{
private readonly IPetStoreClient _petStoreClient;
public HomeController(IPetStoreClient petStoreClient)
{
_petStoreClient = petStoreClient;
}
public async Task<IActionResult> Index()
{
TempData["SoldPetsCount"] = await _petStoreClient.GetSoldPetsCountAsync();
return View();
}
...
}
- To display the number of sold pets on the default site page add this code to
Views\Home\Index.cshtml
:
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
<p>We have injected Pet Store to our DI and retrieved data from API.</p>
<ul>
<li>Number of pets sold: @TempData["SoldPetsCount"]</li>
</ul>
</div>
That's it! We have injected generated client for PetStore API to ASP.NET Core
application via the dependency injection (DI) software design pattern.
Find more Getting Started articles in the documentation and feel free to request new one.