在我试图更新的旧代码中,他们实现了依赖注入,如下所示:
public class Program
{
private IProgramRepository programRepository;
public Program(IProgramRepository repository)
{
this.programRepository = repository;
}
public Program() : this(new EN_Program()) { }
Run Code Online (Sandbox Code Playgroud)
现在在这个程序类中所有的方法都是静态的,所以所有的静态方法实际上都有2个这样的方法:
public static List<Program> GetProgramsByUser(int userId)
{
return GetProgramsByUser(userId, GetDefaultRepository());
}
private static List<Program> GetProgramsByUser(int userId, IProgramRepository repo)
{
return repo.GetProgramsByUser(userId);
}
Run Code Online (Sandbox Code Playgroud)
现在我已经阅读了关于实现DI的其他内容:
这根本不是依赖注入.这实际上明显违反了依赖倒置原则.原则上说"高级模块不应该依赖于低级模块,两者都应该依赖于抽象.细节应该取决于抽象".在上面的代码中,Product.cs本身创建了EN_Program对象.所以它直接依赖于IProgramRepository实现(EN_Program).如果将来另一个实现来自IProgramRepository接口,那么Product.cs代码本身需要更改.因此,有人探讨这不是正确的方法.
看起来旧的开发人员想要从帮助程序类(Program.cs)开始实现DI而没有注入控制器.
假设这个旧代码编写不正确,我是否正确?实施DI时是否有必要从控制器到后端的所有内容都有注射?
恩.控制器需要注入一个辅助类使用的接口(Program.cs) - 然后Program.cs注入一个存储库使用的接口