/
Program.cs
94 lines (76 loc) · 2.19 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// <snippet_all>
using System.Data.Common;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Identity;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using RazorPagesProject.Data;
using RazorPagesProject.Services;
var appBuilder = WebApplication.CreateBuilder(args);
var services = appBuilder.Services;
// Create open SqliteConnection so EF won't automatically close it.
services.AddSingleton<DbConnection>(container =>
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
return connection;
});
services.AddDbContext<ApplicationDbContext>((container, options) =>
{
var connection = container.GetRequiredService<DbConnection>();
options.UseSqlite(connection);
});
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
// <snippet1>
services.AddRazorPages(options =>
{
options.Conventions.AuthorizePage("/SecurePage");
});
// </snippet1>
services.AddHttpClient<IGithubClient, GithubClient>(client =>
{
client.BaseAddress = new Uri("https://api.github.com");
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Yolo", "0.1.0"));
});
// <snippet2>
services.AddScoped<IQuoteService, QuoteService>();
// </snippet2>
services.AddDatabaseDeveloperPageExceptionFilter();
using var app = appBuilder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
using (var scope = app.Services.CreateScope())
{
var container = scope.ServiceProvider;
var db = container.GetRequiredService<ApplicationDbContext>();
db.Database.EnsureCreated();
if (!db.Messages.Any())
{
try
{
db.Initialize();
}
catch (Exception ex)
{
var logger = container.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the database. Error: {Message}", ex.Message);
}
}
}
app.Run();
public partial class Program { }
// </snippet_all>