Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created December 13, 2023 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/3c03c8bb882982f53ac7b04fe96c43b7 to your computer and use it in GitHub Desktop.
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
// ---------------------------------------------------------------------------------
// 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