elsa-core/src/clients/Elsa.Api.Client/Extensions/DependencyInjectionExtensions.cs

48 lines
1.7 KiB
C#
Raw Normal View History

using Elsa.Api.Client.Contracts;
using Elsa.Api.Client.Options;
2023-05-16 18:03:12 +00:00
using Elsa.Api.Client.Resources.WorkflowDefinitions.Contracts;
using Elsa.Api.Client.Services;
2023-04-01 14:15:35 +00:00
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Refit;
namespace Elsa.Api.Client.Extensions;
/// <summary>
/// Provides extension methods for dependency injection.
/// </summary>
2023-04-01 14:15:35 +00:00
[PublicAPI]
public static class DependencyInjectionExtensions
{
/// <summary>
/// Adds the Elsa client to the service collection.
/// </summary>
public static IServiceCollection AddElsaClient(this IServiceCollection services, Action<ElsaClientOptions> configureOptions)
{
services.Configure(configureOptions);
services.AddSingleton<IElsaClient, ElsaClient>();
var settings = new RefitSettings();
2023-04-01 14:15:35 +00:00
services.AddElsaApiClient<IWorkflowDefinitionsApi>(settings);
return services;
}
2023-04-01 14:15:35 +00:00
/// <summary>
/// Adds a refit client for the specified API type.
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="settings">The refit settings.</param>
/// <typeparam name="T">The API type.</typeparam>
public static void AddElsaApiClient<T>(this IServiceCollection services, RefitSettings settings) where T : class
{
2023-05-16 20:37:08 +00:00
services.AddRefitClient<T>(settings)
.ConfigureHttpClient(ConfigureElsaApiHttpClient);
}
2023-04-01 14:15:35 +00:00
private static void ConfigureElsaApiHttpClient(IServiceProvider serviceProvider, HttpClient httpClient)
{
var options = serviceProvider.GetRequiredService<IOptions<ElsaClientOptions>>().Value;
httpClient.BaseAddress = options.BaseAddress;
}
}