DCI: How to implement Context with Dependency Injection?
- by ciscoheat
Most examples of a DCI Context are implemented as a Command pattern. When using Dependency Injection though, it's useful to have the dependencies injected in the constructor and send the parameters into the executing method. Compare the Command pattern class:
public class SomeContext
{
private readonly SomeRole _someRole;
private readonly IRepository<User> _userRepository;
// Everything goes into the constructor for a true encapsuled command.
public SomeContext(SomeRole someRole, IRepository<User> userRepository)
{
_someRole = someRole;
_userRepository = userRepository;
}
public void Execute()
{
_someRole.DoStuff(_userRepository);
}
}
With the Dependency injected class:
public class SomeContext
{
private readonly IRepository<User> _userRepository;
// Only what can be injected using the DI provider.
public SomeContext(IRepository<User> userRepository)
{
_userRepository = userRepository;
}
// Parameters from the executing method
public void Execute(SomeRole someRole)
{
someRole.DoStuff(_userRepository);
}
}
The last one seems a bit nicer, but I've never seen it implemented like this so I'm curious if there are any things to consider.