Created
December 13, 2023 16:28
-
-
Save manoj-choudhari-git/3c03c8bb882982f53ac7b04fe96c43b7 to your computer and use it in GitHub Desktop.
.NET 8 Keyed Services - One Interface Multiple Implementations - Ways to Resolve Implementations
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
// --------------------------------------------------------------------------------- | |
// DEMO 1 - Inject using FromKeyedServices attribute | |
// --------------------------------------------------------------------------------- | |
[Route("api/[controller]")] | |
[ApiController] | |
public class FirstController : ControllerBase | |
{ | |
// This should be email service implementation | |
private readonly IReminderService reminderService; | |
public FirstController([FromKeyedServices("Email")] IReminderService reminderService) | |
{ | |
this.reminderService = reminderService; | |
} | |
[HttpGet("email")] | |
public IActionResult Get() | |
{ | |
this.reminderService.SendReminder(); | |
return Ok(new { Message = "Success" }); | |
} | |
} | |
// --------------------------------------------------------------------------------- | |
// DEMO 2 - Resolve using GetRequiredKeyedService API | |
// --------------------------------------------------------------------------------- | |
[Route("api/[controller]")] | |
[ApiController] | |
public class SecondController : ControllerBase | |
{ | |
// This should be SMS service implementation | |
private readonly IReminderService reminderService; | |
public SecondController(IServiceProvider serviceProvider) | |
{ | |
this.reminderService = serviceProvider | |
.GetRequiredKeyedService<IReminderService>(ReminderType.Sms); ; | |
} | |
[HttpGet("sms")] | |
public IActionResult Get() | |
{ | |
this.reminderService.SendReminder(); | |
return Ok(); | |
} | |
} | |
// --------------------------------------------------------------------------------- | |
// DEMO 3 - Inject using FromKeyedServices attribute | |
// --------------------------------------------------------------------------------- | |
[Route("api/[controller]")] | |
[ApiController] | |
public class ThirdController : ControllerBase | |
{ | |
// This should be Push Notification service implementation | |
private readonly IReminderService reminderService; | |
public ThirdController( | |
[FromKeyedServices(ReminderType.PushNotifications)] | |
IReminderService reminderService) | |
{ | |
this.reminderService = reminderService; | |
} | |
[HttpGet("pushNotifications")] | |
public IActionResult Get() | |
{ | |
this.reminderService.SendReminder(); | |
return Ok(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment