Files
FrontOffice/src/FrontOffice.Main/ConfigureServices.cs

129 lines
5.5 KiB
C#

using Blazored.LocalStorage;
using Grpc.Core;
using Grpc.Net.Client.Web;
using Grpc.Net.Client;
using MudBlazor.Services;
using System.Text.Json;
using System.Text.Json.Serialization;
using FrontOffice.BFF.Category.Protobuf.Protos.Category;
using FrontOffice.BFF.Package.Protobuf.Protos.Package;
using FrontOffice.BFF.Transaction.Protobuf.Protos.Transaction;
using FrontOffice.BFF.User.Protobuf.Protos.User;
using FrontOffice.BFF.UserAddress.Protobuf.Protos.UserAddress;
using FrontOffice.BFF.UserOrder.Protobuf.Protos.UserOrder;
using FrontOffice.BFF.UserWallet.Protobuf.Protos.UserWallet;
using FrontOffice.BFF.ShopingCart.Protobuf.Protos.ShopingCart;
using FrontOffice.Main.Utilities;
namespace Microsoft.Extensions.DependencyInjection;
public static class ConfigureServices
{
public static IServiceCollection AddCommonServices(this IServiceCollection services)
{
services.AddMudServices();
services.AddBlazoredLocalStorage(config =>
{
config.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
config.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
config.JsonSerializerOptions.IgnoreReadOnlyProperties = true;
config.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
config.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
config.JsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip;
config.JsonSerializerOptions.WriteIndented = false;
});
// Access HttpContext for User-Agent
services.AddHttpContextAccessor();
// Register custom services
services.AddSingleton<UserAuthInfo>();
services.AddScoped<AuthService>();
services.AddScoped<AuthDialogService>();
// Storefront services
services.AddScoped<CartService>();
services.AddScoped<ProductService>();
services.AddScoped<CategoryService>();
services.AddScoped<OrderService>();
services.AddScoped<WalletService>();
// Device detection: very light, dependency-free
services.AddTransient<IDeviceDetector, DeviceDetector>();
// PDF generation (Chromium only)
services.AddSingleton<FrontOffice.Main.Utilities.Pdf.IChromiumPdfService, FrontOffice.Main.Utilities.Pdf.ChromiumPdfService>();
return services;
}
public static IServiceCollection AddGrpcServices(this IServiceCollection services, IConfiguration configuration)
{
var baseUrl = configuration["GwUrl"];
// Register optimized HttpClient for gRPC
services.AddScoped(sp =>
{
var handler = new HttpClientHandler
{
MaxConnectionsPerServer = 10,
AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
};
return new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, handler))
{
Timeout = TimeSpan.FromMinutes(10),
BaseAddress = new Uri(baseUrl)
};
});
// Register gRPC clients with authentication
services.AddScoped(CreateAuthenticatedClient<PackageContract.PackageContractClient>);
services.AddScoped(CreateAuthenticatedClient<UserContract.UserContractClient>);
services.AddScoped(CreateAuthenticatedClient<UserAddressContract.UserAddressContractClient>);
services.AddScoped(CreateAuthenticatedClient<UserOrderContract.UserOrderContractClient>);
services.AddScoped(CreateAuthenticatedClient<UserWalletContract.UserWalletContractClient>);
services.AddScoped(CreateAuthenticatedClient<CategoryContract.CategoryContractClient>);
// Products gRPC
services.AddScoped(CreateAuthenticatedClient<FrontOffice.BFF.Products.Protobuf.Protos.Products.ProductsContract.ProductsContractClient>);
services.AddScoped(CreateAuthenticatedClient<TransactionContract.TransactionContractClient>);
services.AddScoped(CreateAuthenticatedClient<ShopingCartContract.ShopingCartContractClient>);
return services;
}
private static TClient CreateAuthenticatedClient<TClient>(IServiceProvider sp)
where TClient : class
{
var httpClient = sp.GetRequiredService<HttpClient>();
var localStorage = sp.GetRequiredService<ILocalStorageService>();
var baseUrl = httpClient.BaseAddress?.ToString() ?? throw new InvalidOperationException("Base URL not configured");
var credentials = CallCredentials.FromInterceptor(async (context, metadata) =>
{
try
{
var token = await localStorage.GetItemAsync<string>("auth:token");
if (!string.IsNullOrWhiteSpace(token))
{
metadata.Add("Authorization", $"Bearer {token}");
}
}
catch (Exception ex)
{
#if DEBUG
Console.WriteLine($"Token retrieval error: {ex.Message}");
#endif
}
});
var channel = GrpcChannel.ForAddress(baseUrl, new GrpcChannelOptions
{
UnsafeUseInsecureChannelCallCredentials = true,
Credentials = ChannelCredentials.Create(new SslCredentials(), credentials),
HttpClient = httpClient,
MaxReceiveMessageSize = 1000 * 1024 * 1024, // 1 GB
MaxSendMessageSize = 1000 * 1024 * 1024 // 1 GB
});
return (TClient)Activator.CreateInstance(typeof(TClient), channel)!;
}
}