Dependency Injection: where to store dependencies used by only one method?
Posted
by
simoneL
on Programmers
See other posts from Programmers
or by simoneL
Published on 2014-08-22T09:58:22Z
Indexed on
2014/08/22
10:26 UTC
Read the original article
Hit count: 160
c#
|dependency-injection
I developing a project integrated with Dependency Injection (just for reference, I'm using Unity).
The problem is that I have some Manager classes with several methods and in many cases I have dependencies used only in one method.
public class UserManager : IUserManager
{
private UserRepository UserRepository {get;set;}
private TeamRepository TeamRepository {get;set;}
private CacheRepository CacheRepository {get;set;}
private WorkgroupRepository WorkgroupRepository {get;set;}
public UserManager(UserRepository userRepository,
TeamRepository teamRepository,
CacheRepository cacheRepository ,
WorkgroupRepository workgroupRepository,
... // Many other dependencies
)
{
UserRepository = userRepository;
TeamRepository = teamRepository;
CacheRepository = cacheRepository ;
WorkgroupRepository = workgroupRepository;
... // Setting the remaining dependencies
}
public void GetLatestUser(){
// Uses only UserRepository
}
public void GetUsersByTeam(int teamID){
// Uses only TeamRepository
}
public void GetUserHistory(){
// Uses only CacheRepository
}
public void GetUsersByWorkgroup(int workgroupID){
// Uses only workgroupRepository
}
}
The UserManager is instantiated in this way:
DependencyFactory<IUserManager>();
Note: DependencyFactory is just a wrapper to simplify the access to the UnityContainer
Is it OK to have classes like that in the example? Is there a better way to implement avoiding to instantiate all the unnecessary dependencies?
© Programmers or respective owner