I have been wondering for quite some time on some issues while using dependency injection: In a laye

Need your ASSIGNMENT done? Use our paper writing service to score better and meet your deadline.


Order a Similar Paper Order a Different Paper

I have been wondering for quite some time on some issues while using dependency injection:

In a layered application, I normally inject repositories into the application service using constructor injection:

public class SomeService
{
    private IRepositoryA _repoA;
    private IRepositoryB _repoB;
    private IRepositoryC _repoC;

    public SomeService(IRepositoryA repositoryA,
                       IRepositoryB repositoryB,
                       IRepositoryC repositoryC
                       /* Other dependencies*/)
    {
        _repoA = repositoryA;
        _repoB = repositoryB;
        _repoC = repositoryC;
    }

    public void SomeMethod1()
    {
        //Do something with repo A and B
    }

    public void SomeMethod2()
    {
        //Do something with repo C
    }

    //Other methods
}
The problems with this are:

When the service becomes complicated, the number of dependencies will grow more and more, and soon the constructor will become ugly with lots of parameters. It might be the service is doing too many things (violate SRP) and better be separated into several classes, but I think this situation is not uncommon so I’m curious how others solve this

SomeMethod1() only uses repo A and B, but when client calls it, the service is created with all repositories, meaning it has more dependencies than it needs.

To address those 2 issues, I see some people have another abstraction, which is repository factory

public interface IRepositoryFactory
{
    T GetRepository<T>() where T : IRepository;
}

public class RepositoryFactory
{
    public T GetRepository<T>()
    {
        //Use IoC to return correct IRepository
    }
}
and inject factory into service class:

public class SomeService
{
    private IRepositoryFactory _factory;
    public SomeService(IRepositoryFactory factory)
    {
        _factory = factory;
    }

    public void SomeMethod1()
    {
        IRepositoryA repoA = _factory.GetRepository<IRepositoryA>();
        IRepositoryB repoB = _factory.GetRepository<IRepositoryB>();
        //Use repo A and B
    }

    public void SomeMethod2()
    {
        IRepositoryC repoC = _factory.GetRepository<IRepositoryC>();
        //Use repo C
    }

    //Other methods
}
This does solve the 2 problems above, but there are a few other issues:

RepositoryFactory is using IoC as a service locator, which is considered as anti-pattern by many people
RepositoryFactory has a dependency on IoC framework now, which might be undesirable in dependency injection (because as I understand, the application should have as little understanding about the IoC as they can, except for composition root, which is at the top of the application)
So is this a good approach to use?