Skip to content

Commit 8716527

Browse files
committed
Refactor ModularStartup to use HostingStartup
1 parent f2945c6 commit 8716527

File tree

4 files changed

+61
-74
lines changed

4 files changed

+61
-74
lines changed

api/MyApp/Configure.Auth.cs

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
using Microsoft.Extensions.DependencyInjection;
22
using ServiceStack;
3+
using ServiceStack.Caching;
34
using ServiceStack.Auth;
45
using ServiceStack.FluentValidation;
56

7+
[assembly: HostingStartup(typeof(MyApp.ConfigureAuth))]
8+
69
namespace MyApp
710
{
811
// Add any additional metadata properties you want to store in the Users Typed Session
@@ -23,28 +26,30 @@ public CustomRegistrationValidator()
2326
}
2427
}
2528

26-
public class ConfigureAuth : IConfigureAppHost, IConfigureServices
29+
public class ConfigureAuth : IHostingStartup
2730
{
28-
public void Configure(IServiceCollection services)
29-
{
30-
//services.AddSingleton<ICacheClient>(new MemoryCacheClient()); //Store User Sessions in Memory Cache (default)
31-
}
31+
public void Configure(IWebHostBuilder builder) => builder
32+
//.ConfigureServices(services => services.AddSingleton<ICacheClient>(new MemoryCacheClient()))
33+
.ConfigureAppHost(appHost => {
34+
var appSettings = appHost.AppSettings;
35+
appHost.Plugins.Add(new AuthFeature(() => new CustomUserSession(),
36+
new IAuthProvider[] {
37+
new JwtAuthProvider(appSettings) {
38+
RequireSecureConnection = !appHost.IsDevelopmentEnvironment(),
39+
AuthKey = AesUtils.CreateKey(),
40+
UseTokenCookie = true,
41+
},
42+
new CredentialsAuthProvider(appSettings), /* Sign In with Username / Password credentials */
43+
new FacebookAuthProvider(appSettings), /* Create App https://developers.facebook.com/apps */
44+
new GoogleAuthProvider(
45+
appSettings), /* Create App https://console.developers.google.com/apis/credentials */
46+
new MicrosoftGraphAuthProvider(appSettings), /* Create App https://apps.dev.microsoft.com */
47+
}));
3248

33-
public void Configure(IAppHost appHost)
34-
{
35-
var AppSettings = appHost.AppSettings;
36-
appHost.Plugins.Add(new AuthFeature(() => new CustomUserSession(),
37-
new IAuthProvider[] {
38-
new CredentialsAuthProvider(AppSettings), /* Sign In with Username / Password credentials */
39-
new FacebookAuthProvider(AppSettings), /* Create App https://developers.facebook.com/apps */
40-
new GoogleAuthProvider(AppSettings), /* Create App https://console.developers.google.com/apis/credentials */
41-
new MicrosoftGraphAuthProvider(AppSettings), /* Create App https://apps.dev.microsoft.com */
42-
}));
49+
appHost.Plugins.Add(new RegistrationFeature()); //Enable /register Service
4350

44-
appHost.Plugins.Add(new RegistrationFeature()); //Enable /register Service
45-
46-
//override the default registration validation with your own custom implementation
47-
appHost.RegisterAs<CustomRegistrationValidator, IValidator<Register>>();
48-
}
51+
//override the default registration validation with your own custom implementation
52+
appHost.RegisterAs<CustomRegistrationValidator, IValidator<Register>>();
53+
});
4954
}
50-
}
55+
}

api/MyApp/Configure.AuthRepository.cs

Lines changed: 19 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
using System;
2-
using System.Collections.Generic;
3-
using Microsoft.Extensions.DependencyInjection;
42
using ServiceStack;
53
using ServiceStack.Web;
64
using ServiceStack.Data;
75
using ServiceStack.Auth;
86
using ServiceStack.Configuration;
9-
using ServiceStack.OrmLite;
7+
8+
[assembly: HostingStartup(typeof(MyApp.ConfigureAuthRepository))]
109

1110
namespace MyApp
1211
{
@@ -20,42 +19,35 @@ public class AppUser : UserAuth
2019

2120
public class AppUserAuthEvents : AuthEvents
2221
{
23-
public override void OnAuthenticated(IRequest req, IAuthSession session, IServiceBase authService,
24-
IAuthTokens tokens, Dictionary<string, string> authInfo)
22+
public override async Task OnAuthenticatedAsync(IRequest httpReq, IAuthSession session, IServiceBase authService,
23+
IAuthTokens tokens, Dictionary<string, string> authInfo, CancellationToken token = default)
2524
{
26-
var authRepo = HostContext.AppHost.GetAuthRepository(req);
25+
var authRepo = HostContext.AppHost.GetAuthRepositoryAsync(httpReq);
2726
using (authRepo as IDisposable)
2827
{
29-
var userAuth = (AppUser)authRepo.GetUserAuth(session.UserAuthId);
28+
var userAuth = (AppUser)await authRepo.GetUserAuthAsync(session.UserAuthId, token);
3029
userAuth.ProfileUrl = session.GetProfileUrl();
31-
userAuth.LastLoginIp = req.UserHostAddress;
30+
userAuth.LastLoginIp = httpReq.UserHostAddress;
3231
userAuth.LastLoginDate = DateTime.UtcNow;
33-
authRepo.SaveUserAuth(userAuth);
32+
await authRepo.SaveUserAuthAsync(userAuth, token);
3433
}
3534
}
3635
}
3736

38-
public class ConfigureAuthRepository : IConfigureAppHost, IConfigureServices, IPreInitPlugin
37+
public class ConfigureAuthRepository : IHostingStartup
3938
{
40-
public void Configure(IServiceCollection services)
41-
{
42-
services.AddSingleton<IAuthRepository>(c =>
39+
public void Configure(IWebHostBuilder builder) => builder
40+
.ConfigureServices(services => services.AddSingleton<IAuthRepository>(c =>
4341
new OrmLiteAuthRepository<AppUser, UserAuthDetails>(c.Resolve<IDbConnectionFactory>()) {
4442
UseDistinctRoleTables = true
45-
});
46-
}
47-
48-
public void Configure(IAppHost appHost)
49-
{
50-
var authRepo = appHost.Resolve<IAuthRepository>();
51-
authRepo.InitSchema();
52-
CreateUser(authRepo, "admin@email.com", "Admin User", "p@55wOrd", roles:new[]{ RoleNames.Admin });
53-
}
54-
55-
public void BeforePluginsLoaded(IAppHost appHost)
56-
{
57-
appHost.AssertPlugin<AuthFeature>().AuthEvents.Add(new AppUserAuthEvents());
58-
}
43+
}))
44+
.ConfigureAppHost(appHost => {
45+
var authRepo = appHost.Resolve<IAuthRepository>();
46+
authRepo.InitSchema();
47+
CreateUser(authRepo, "admin@email.com", "Admin User", "p@55wOrd", roles:new[]{ RoleNames.Admin });
48+
}, afterConfigure: appHost => {
49+
appHost.AssertPlugin<AuthFeature>().AuthEvents.Add(new AppUserAuthEvents());
50+
});
5951

6052
// Add initial Users to the configured Auth Repository
6153
public void CreateUser(IAuthRepository authRepo, string email, string name, string password, string[] roles)

api/MyApp/Configure.Db.cs

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
using Microsoft.Extensions.Configuration;
2-
using Microsoft.Extensions.DependencyInjection;
31
using ServiceStack;
42
using ServiceStack.Data;
5-
using ServiceStack.DataAnnotations;
63
using ServiceStack.OrmLite;
74

5+
[assembly: HostingStartup(typeof(MyApp.ConfigureDb))]
6+
87
namespace MyApp
98
{
109
// Example Data Model
@@ -15,29 +14,22 @@ namespace MyApp
1514
// public string Name { get; set; }
1615
// }
1716

18-
public class ConfigureDb : IConfigureServices, IConfigureAppHost
17+
public class ConfigureDb : IHostingStartup
1918
{
20-
IConfiguration Configuration { get; }
21-
public ConfigureDb(IConfiguration configuration) => Configuration = configuration;
22-
23-
public void Configure(IServiceCollection services)
24-
{
25-
services.AddSingleton<IDbConnectionFactory>(new OrmLiteConnectionFactory(
26-
Configuration.GetConnectionString("DefaultConnection")
19+
public void Configure(IWebHostBuilder builder) => builder
20+
.ConfigureServices(services => services.AddSingleton<IDbConnectionFactory>(new OrmLiteConnectionFactory(
21+
builder.GetSetting("ConnectionStrings:DefaultConnection")
2722
?? ":memory:",
28-
SqliteDialect.Provider));
29-
}
30-
31-
public void Configure(IAppHost appHost)
32-
{
33-
appHost.GetPlugin<SharpPagesFeature>()?.ScriptMethods.Add(new DbScriptsAsync());
23+
SqliteDialect.Provider)))
24+
.ConfigureAppHost(appHost => {
25+
appHost.GetPlugin<SharpPagesFeature>()?.ScriptMethods.Add(new DbScriptsAsync());
3426

35-
// Create non-existing Table and add Seed Data Example
36-
// using var db = appHost.Resolve<IDbConnectionFactory>().Open();
37-
// if (db.CreateTableIfNotExists<MyTable>())
38-
// {
39-
// db.Insert(new MyTable { Name = "Seed Data for new MyTable" });
40-
// }
41-
}
27+
// Create non-existing Table and add Seed Data Example
28+
// using var db = appHost.Resolve<IDbConnectionFactory>().Open();
29+
// if (db.CreateTableIfNotExists<MyTable>())
30+
// {
31+
// db.Insert(new MyTable { Name = "Seed Data for new MyTable" });
32+
// }
33+
});
4234
}
4335
}

api/MyApp/Program.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
using ServiceStack;
33

44
var builder = WebApplication.CreateBuilder(args);
5-
6-
builder.Services.AddModularStartup<AppHost>(builder.Configuration);
75
builder.Services.ConfigureNonBreakingSameSiteCookies(builder.Environment);
86

97
var app = builder.Build();

0 commit comments

Comments
 (0)