-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
52 lines (39 loc) · 1.63 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
var builder = WebApplication.CreateBuilder(args);
// Keyed services
// https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-9.0#keyed-services
builder.Services.AddKeyedSingleton<INotificationService, SmsService>(Constants.SMS);
builder.Services.AddKeyedSingleton<INotificationService, EmailService>(Constants.Email);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.MapPost("/notify", (Notification notification) =>
{
var notificationService = GetNotificationService(notification, app.Services);
notificationService?.Notify(notification.Message);
return Results.Created();
//https://github.com/ibrahimatay/Csharp-Features/blob/master/StaticLocalFunctions/Program.cs
static INotificationService? GetNotificationService(Notification notification, IServiceProvider serviceProvider) => notification.Channel switch
{
"sms" => serviceProvider.GetKeyedService<INotificationService>(Constants.SMS),
"email" => serviceProvider.GetKeyedService<INotificationService>(Constants.Email),
_ => throw new NotSupportedException()
};
});
app.Run();
public record Notification(string Message, string Channel);
static class Constants
{
public const string SMS = "SMS";
public const string Email = "Email";
}
interface INotificationService
{
void Notify(string message);
}
class SmsService : INotificationService
{
public void Notify(string message)=> Console.WriteLine($"Sent SMS! Message: {message}");
}
class EmailService: INotificationService
{
public void Notify(string message)=> Console.WriteLine($"Sent Email! Message: {message}");
}