forked from FarmMaps/FarmMapsApiClient
74 lines
2.8 KiB
C#
74 lines
2.8 KiB
C#
using System;
|
|
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;
|
|
using Microsoft.Extensions.Logging;
|
|
using Serilog;
|
|
using Serilog.Events;
|
|
using Serilog.Filters;
|
|
|
|
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)
|
|
.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;
|
|
|
|
Configure(serviceCollection);
|
|
|
|
var serviceProvider = serviceCollection.BuildServiceProvider();
|
|
|
|
ConfigureLogger(serviceProvider);
|
|
|
|
await serviceProvider.GetService<FarmmapsApiService>().AuthenticateAsync();
|
|
// await serviceProvider.GetService<FarmmapsEventHub>().StartEventHub();
|
|
|
|
await serviceProvider.GetRequiredService<T>().RunAsync();
|
|
}
|
|
|
|
protected abstract void Configure(IServiceCollection serviceCollection);
|
|
|
|
private static void ConfigureLogger(IServiceProvider serviceProvider)
|
|
{
|
|
var isService = Matching.FromSource("Microsoft");
|
|
|
|
Log.Logger = new LoggerConfiguration()
|
|
.MinimumLevel.Information()
|
|
.WriteTo.Logger(l => l.Filter.ByIncludingOnly(isService)
|
|
.WriteTo.Console(LogEventLevel.Warning))
|
|
.WriteTo.File(path: "Logs/log.log", rollingInterval: RollingInterval.Day)
|
|
.CreateLogger();
|
|
|
|
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
|
|
loggerFactory.AddSerilog();
|
|
}
|
|
}
|
|
} |