samedi 10 juillet 2021

ASP.NET Core Dependency Injection Single aggregate class instead of multiple separate constructor injections

In my ASP.NET Core Web API I have several controllers which accept more than 4-5 parameters in their constructors and this doesn't look good to me. I'm thinking of creating an aggregate class which would have all the separate objects I frequently use. I mean, for example, instead of this:

public SomeController : Controller
{
    public SomeController(IService1 service1, IService2 service2, Config1 config1, Config2 config2) { }
}

to write something like this:

public class MyToolkit // of course registered in DI services.AddSingleton<MyToolkit>()
{
    public MyToolkit(IService1 service1, IService2 service2, Config1 config1, Config2 config2)
    {
        ...
    }

    public IService1 Service1 { get; }
    public IService2 Service2 { get; }
    public Config1 Config1 { get; }
    public Config2 Config2 { get; }
}

public SomeController : Controller
{
    private readonly MyToolkit _toolkit;
    public SomeController(MyToolkit toolkit) { _toolkit = toolkit; }

    [HttpGet]
    public IActionResult GetSomething()
    {
        return _toolkit.Service1.GetSomething();
    }
}

Does this approach (MyToolkit class) violate any modern design principles? Is this approach considered anti-pattern?

Aucun commentaire:

Enregistrer un commentaire