© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
38 replies
Mango

Need to make an IO call to register a service

using System.Net.Http.Headers;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Erp.Core.Extensions;

public static class ServiceCollectionExtensions
{
    /// <summary>
    /// Adds the Tenant API for retrieving the <see cref="TenantContext"/>.
    /// <br />
    /// This is required by the ASP.Net application to run. Requires the following value set in appsettings.json in the Configuration section.
    /// - TenantEndpoint
    /// </summary>
    /// <param name="services"></param>
    /// <exception cref="HttpRequestException"></exception>
    public static void AddTenantContext(this IServiceCollection services)
    {
        services.AddScoped(sp =>
        {
            var cache = sp.GetRequiredService<IMemoryCache>();
            var configuration = sp.GetRequiredService<IConfiguration>();
            var factory = sp.GetRequiredService<IHttpClientFactory>();
            var accessor = sp.GetRequiredService<IHttpContextAccessor>();

            var host = accessor.HttpContext!.Request.Host.Host;
            
            return cache.GetOrCreate($"tenant.{host}", cacheEntry =>
            {
                cacheEntry.SlidingExpiration = TimeSpan.FromHours(8);

                var endpoint = configuration.GetValue<string>("Configuration:TenantEndpoint");
                ArgumentException.ThrowIfNullOrEmpty(endpoint);

                using var client = factory.CreateClient();
                var request = new HttpRequestMessage(HttpMethod.Get, $"{endpoint}/api/retrieve-tenant/{host}");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "");

                var response = client.Send(request);

                if (!response.IsSuccessStatusCode)
                    throw new HttpRequestException(response.StatusCode.ToString());

                var content = response.Content.ToString();
                ArgumentException.ThrowIfNullOrEmpty(content);
                
                return new Tenant(Guid.Parse(content));
            });
        });
    }
}
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Erp.Core.Extensions;

public static class ServiceCollectionExtensions
{
    /// <summary>
    /// Adds the Tenant API for retrieving the <see cref="TenantContext"/>.
    /// <br />
    /// This is required by the ASP.Net application to run. Requires the following value set in appsettings.json in the Configuration section.
    /// - TenantEndpoint
    /// </summary>
    /// <param name="services"></param>
    /// <exception cref="HttpRequestException"></exception>
    public static void AddTenantContext(this IServiceCollection services)
    {
        services.AddScoped(sp =>
        {
            var cache = sp.GetRequiredService<IMemoryCache>();
            var configuration = sp.GetRequiredService<IConfiguration>();
            var factory = sp.GetRequiredService<IHttpClientFactory>();
            var accessor = sp.GetRequiredService<IHttpContextAccessor>();

            var host = accessor.HttpContext!.Request.Host.Host;
            
            return cache.GetOrCreate($"tenant.{host}", cacheEntry =>
            {
                cacheEntry.SlidingExpiration = TimeSpan.FromHours(8);

                var endpoint = configuration.GetValue<string>("Configuration:TenantEndpoint");
                ArgumentException.ThrowIfNullOrEmpty(endpoint);

                using var client = factory.CreateClient();
                var request = new HttpRequestMessage(HttpMethod.Get, $"{endpoint}/api/retrieve-tenant/{host}");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "");

                var response = client.Send(request);

                if (!response.IsSuccessStatusCode)
                    throw new HttpRequestException(response.StatusCode.ToString());

                var content = response.Content.ToString();
                ArgumentException.ThrowIfNullOrEmpty(content);
                
                return new Tenant(Guid.Parse(content));
            });
        });
    }
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources
Was this page helpful?

Similar Threads

Recent Announcements

Similar Threads

❔ how to make an API call
C#CC# / help
3y ago
ServiceFabric DataContract exception serialization and ServiceProxy.Create
C#CC# / help
2y ago
I need help for register
C#CC# / help
4y ago
IO threads - why need them?
C#CC# / help
2y ago