DCI 上下文的大多数示例都是作为命令模式实现的。但是,在使用依赖注入时,将依赖注入到构造函数中并将参数发送到执行方法中很有用。比较命令模式类:
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);
}
}
使用依赖注入类:
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);
}
}
最后一个似乎更好一些,但我从未见过它像这样实现,所以我很好奇是否有任何事情需要考虑。