DEV Community

Ahmed Shah
Ahmed Shah

Posted on

๐Ÿ”‘ Keyed Services in .NET Core 8: The Death of the Factory Pattern? ๐Ÿ”‘

In the world of .NET Core 8, we're always looking for ways to write cleaner, more maintainable code. One of the most significant recent developments in this area is the introduction of "Keyed Services" ๐ŸŽ‰.

Keyed Services allow us to register multiple implementations of an interface with a unique key ๐Ÿ”‘. We can then retrieve the specific implementation we need at runtime using this key. This is a significant improvement over the traditional Factory Pattern, where we had to manually control the creation of our objects ๐Ÿญ.

With this approach, we no longer need to create complex factories or use service locators. Instead, we can rely on the built-in dependency injection container to handle this for us ๐Ÿงฐ.

Does this mean the Factory Pattern is dead ๐Ÿ’€? Not necessarily. There are still scenarios where the Factory Pattern might be the right choice. However, Keyed Services provide a powerful alternative that can simplify our code and make it more maintainable ๐Ÿš€.

What are your thoughts on this? Have you used Keyed Services in your projects?
Image description

Top comments (5)

Collapse
 
karenpayneoregon profile image
Karen Payne

You could provide a working example hosted on GitHub.

Collapse
 
ahmedshahjr profile image
Ahmed Shah

@karenpayneoregon here is the practical implementation and git hub code link please like. dev.to/ahmedshahjr/unlock-your-bus...

Collapse
 
ahmedshahjr profile image
Ahmed Shah

sorry for the late response was out sure definitely will create one example keep following
linkedin.com/in/ahmedshahjr/

Collapse
 
mrmirtel21 profile image
MrMirtel21

Hey IKeyedServiceProvider is not injectable as far as I know, it should use IServiceProvider instead for that

Collapse
 
ahmedshahjr profile image
Ahmed Shah

using KeyedServices.Services;
using Microsoft.AspNetCore.Mvc;

namespace KeyedServices.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IEmailService _emailService;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, [FromKeyedServices(nameof(EmailServiceEnum.Gmail))] IEmailService emailService)
    {
        _logger = logger;
        _emailService = emailService;
    }

    [HttpGet(Name = "SendEmail")]
    public string SendEmail()
    {
       return _emailService.SendEmailAsync("Sending Email From");
    }
}
Enter fullscreen mode Exit fullscreen mode

}

its can be intejecate using fromkeyedservice interface.

github.com/ahmedshahjr/Articles/tr...
my repe link