FarmMapsApiClient_WURtest/FarmmapsApi/FarmmapsProgram.cs

79 lines
3.0 KiB
C#
Raw Normal View History

2021-04-19 11:14:30 +00:00
using System;
2020-04-08 18:23:22 +00:00
using System.Net.Http;
using System.Threading.Tasks;
using FarmmapsApi.HttpMessageHandlers;
using FarmmapsApi.Models;
using FarmmapsApi.Services;
using IdentityModel.Client;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
2021-04-19 11:14:30 +00:00
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Filters;
2020-04-08 18:23:22 +00:00
namespace FarmmapsApi
{
public abstract class FarmmapsProgram<T> where T : class, IApplication
{
public async Task Start(string[] args)
{
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile("appsettings.secrets.json", false, true)
2020-04-08 18:23:22 +00:00
.Build();
var configuration = config.Get<Configuration>();
var serviceCollection = new ServiceCollection()
.AddSingleton(configuration)
.AddSingleton<IDiscoveryCache>(sp =>
{
var httpFactory = sp.GetRequiredService<IHttpClientFactory>();
return new DiscoveryCache(configuration.DiscoveryEndpointUrl,
() => httpFactory.CreateClient());
})
.AddSingleton<HttpClientSettings>()
.AddSingleton<FarmmapsEventHub>()
.AddSingleton<T>()
.AddTransient<OpenIdConnectService>()
.AddTransient<FarmmapsAuthenticationHandler>()
.AddTransient<GeneralService>()
.AddHttpClient<FarmmapsApiService>()
.AddHttpMessageHandler<FarmmapsAuthenticationHandler>()
.Services;
2021-04-19 11:16:33 +00:00
2020-04-08 18:23:22 +00:00
Configure(serviceCollection);
var serviceProvider = serviceCollection.BuildServiceProvider();
2021-04-19 11:14:30 +00:00
ConfigureLogger(serviceProvider);
2021-04-19 11:16:33 +00:00
2020-04-08 18:23:22 +00:00
await serviceProvider.GetService<FarmmapsApiService>().AuthenticateAsync();
// await serviceProvider.GetService<FarmmapsEventHub>().StartEventHub();
await serviceProvider.GetRequiredService<T>().RunAsync();
}
protected abstract void Configure(IServiceCollection serviceCollection);
2021-04-19 11:16:33 +00:00
2021-04-19 11:14:30 +00:00
private static void ConfigureLogger(IServiceProvider serviceProvider)
{
2021-04-19 11:16:33 +00:00
var isMicrosoftNamespace = Matching.FromSource("Microsoft");
2021-04-19 12:03:43 +00:00
var isSystem = Matching.FromSource("System");
2021-04-19 11:16:33 +00:00
2021-04-19 11:14:30 +00:00
Log.Logger = new LoggerConfiguration()
2021-04-19 12:03:43 +00:00
.MinimumLevel.Verbose()
.WriteTo.Logger(l =>
l.WriteTo.Logger(l2 => l2
.Filter.ByExcluding(v => isMicrosoftNamespace(v) || isSystem(v))
.WriteTo.Console())
)
2021-04-19 11:14:30 +00:00
.WriteTo.File(path: "Logs/log.log", rollingInterval: RollingInterval.Day)
.CreateLogger();
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
loggerFactory.AddSerilog();
2021-04-19 11:16:33 +00:00
}
2020-04-08 18:23:22 +00:00
}
}