1

We are currently using Dependency Injection for the first time in our of our projects developed in ASP.NET using Autofac as the IoC container.

Everything is working fine, but we have a question about injecting services into our controllers.

Below is an example:

ISupplierService

/// <summary>
/// Service interface for working with the <see cref="ISupplier"/>
/// </summary>
public interface ISupplierService
{
    /// <summary>
    /// Get the supplier by Id
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    ISupplier GetSupplierById(int id);
}

IArticleService

/// <summary>
/// Service interface when working with the <see cref="IArticle"/>
/// </summary>
public interface IArticleService
{
    /// <summary>
    /// Get article by id
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    IArticle GetArticleById(int id);
}

IoC register services

builder.RegisterAssemblyTypes(Assembly.Load("Project.Core"))
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

Now in one of our controllers we need the supplier and article service, so we can inject these both in the constructor of the controller.

public class HomeController : Controller
{
    private IArticleService _articleService;
    private ISupplierService _supplierService;

    public HomeController(IArticleService articleService, ISupplierService supplierService)
    {
        _articleService = articleService;
        _supplierService= supplierService;
    }
}

But what if we need for 4 or 5 services in our controller or even more?

Is it bad practise for Dependency Injection to create some sort of Service Factory where we resolve instances of the needed services using Autofac? In this way we only need to inject the factory in our controller and then we can call the correct service from our factory when we need it.

Mivaweb
  • 5,580
  • 3
  • 27
  • 53
  • 1
    Have a look at https://stackoverflow.com/questions/2420193/how-to-avoid-dependency-injection-constructor-madness – Cyril Durand Jul 05 '17 at 06:53
  • It is not at all unusual to pass 4-5 or (many) more interfaces into a constructor. This is why IoC containers are so helpful! You will get used to it. – John Wu Jul 05 '17 at 07:09
  • @CyrilDurand Thanks for this link! The Facade Service is really something useful to look into and could be the solution! – Mivaweb Jul 05 '17 at 07:13

0 Answers0