Created
January 22, 2022 15:04
-
-
Save utarn/c5636275a6ff99d104901361f5507bb2 to your computer and use it in GitHub Desktop.
Dependency Injection for console app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace AppClient | |
{ | |
static class Program | |
{ | |
private static IConfiguration _configuration; | |
static async Task Main() | |
{ | |
var builder = new ConfigurationBuilder() | |
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); | |
_configuration = builder.Build(); | |
var services = new ServiceCollection(); | |
ConfigureServices(services); | |
using (ServiceProvider serviceProvider = services.BuildServiceProvider()) | |
{ | |
var form1 = serviceProvider.GetRequiredService<Form1>(); | |
var userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>(); | |
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); | |
await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager, roleManager); | |
form1.Run(); | |
} | |
} | |
private static void ConfigureServices(ServiceCollection services) | |
{ | |
var dataConfiguration = new DataConfiguration(); | |
_configuration.Bind("dataConfig", dataConfiguration); | |
services.AddSingleton(dataConfiguration); | |
services.AddSingleton<IConfiguration>(_ => _configuration); | |
services.AddLogging(configure => configure.AddConsole()) | |
.AddScoped<ApplicationDbContext, ApplicationDbContext>() | |
.AddScoped<Form1, Form1>(); | |
services.AddDbContext<ApplicationDbContext>(options => | |
options.UseSqlite( | |
_configuration.GetConnectionString("DefaultConnection"))); | |
services.AddHttpClient("HttpClientWithSSLUntrusted").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler | |
{ | |
ClientCertificateOptions = ClientCertificateOption.Manual, | |
ServerCertificateCustomValidationCallback = | |
(httpRequestMessage, cert, cetChain, policyErrors) => true | |
}); | |
services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true) | |
.AddEntityFrameworkStores<ApplicationDbContext>() | |
.AddDefaultTokenProviders(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment