内置 DI

ASP.NET Core 内置 DI,当然你也可以使用别的 DI 实现。

Full Stack 02 - 图1

换用 PostgreSQL

Startup 有注释的位置就是更改:

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. // Store connection string as a var
  4. var connectionString = Configuration.GetConnectionString("DefaultConnection");
  5. // Store assembly for migrations
  6. var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
  7. // Replace DbContext database form SqLite in template to Postgres
  8. services.AddDbContext<ApplicationDbContext>(options =>
  9. options.UseNpgsql(connectionString));
  10. services.AddIdentity<ApplicationUser, IdentityRole>()
  11. .AddEntityFrameworkStores<ApplicationDbContext>()
  12. .AddDefaultTokenProviders();
  13. services.AddMvc();
  14. services.Configure<IISOptions>(iis =>
  15. {
  16. iis.AuthenticationDisplayName = "Windows";
  17. iis.AutomaticAuthentication = false;
  18. });
  19. var builder = services.AddIdentityServer(options =>
  20. {
  21. options.Events.RaiseErrorEvents = true;
  22. options.Events.RaiseInformationEvents = true;
  23. options.Events.RaiseFailureEvents = true;
  24. options.Events.RaiseSuccessEvents = true;
  25. })
  26. // Use out Postgres Database for storing configuration data
  27. .AddConfigurationStore(configDb =>
  28. {
  29. configDb.ConfigureDbContext = db => db.UseNpgsql(connectionString,
  30. sql => sql.MigrationsAssembly(migrationsAssembly));
  31. })
  32. // Use out Postgres Database for storing operational data
  33. .AddOperationalStore(operationalDb =>
  34. {
  35. operationalDb.ConfigureDbContext = db => db.UseNpgsql(connectionString,
  36. sql => sql.MigrationsAssembly(migrationsAssembly));
  37. })
  38. .AddAspNetIdentity<ApplicationUser>();
  39. if (Environment.IsDevelopment())
  40. {
  41. builder.AddDeveloperSigningCredential();
  42. }
  43. else
  44. {
  45. throw new Exception("need to configure key material");
  46. }
  47. services.AddAuthentication()
  48. .AddGoogle(options =>
  49. {
  50. options.ClientId = "708996912208-9m4dkjb5hscn7cjrn5u0r4tbgkbj1fko.apps.googleusercontent.com";
  51. options.ClientSecret = "wdfPY6t8H8cecgjlxud__4Gh";
  52. });
  53. }

ApplicationUser 是我们回头要自定义使用的。
它继承自 IdentityUser,IdentityUser 是 Microsoft.AspNetCore.Identity.IdentityUser 的默认实现。

appsettings.json:

  1. {
  2. "ConnectionStrings": {
  3. "DefaultConnection": "Server=localhost;Port=5432;Database=archdb_dev;User Id=arch_agent;Password=~pass123~;"
  4. }
  5. }