目标是使用IoC并能够模拟单元测试的依赖项。
项目:具有多个类库的.NET Core Web API
我在我的IoC上使用Microsoft.Extensions.DependencyInjection,如果它支持我想要实现的功能,我想继续使用它。
问题:我的程序集中(类库)中至少有一个类有一个需要模拟的依赖项(例如,使用Moq)。我完全理解我可以使用构造函数注入来注入接口,但这并不适合这个场景。
我只是想在我的程序集中完成的工作就是使用我在Web API的Startup类中启动的容器来解析依赖项。
我该怎么做呢?如果这是不可能的,什么可能是另一种方法来完成相同的事情,即模拟我的打印机而不使用依赖注入?
下面是一些示例代码,希望能澄清这一点。
Web API的Startup.cs (引用了定义打印机的程序集)
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IPrinter, Printer>();
}
在一个不同的程序集中,我想解析一个使用相同容器的Printer实例。
public interface IPrinter
{
void Print(string text);
}
public class Printer : IPrinter
{
public void Print(string text)
{
Console.WriteLine("Printing: " + text);
}
}
public class Task
{
public void PrintSomething(string text)
{
//do not 'new up' but resolve it from the container of Startup.cs
var printer = new Printer();
printer.Print(text);
}
}
发布于 2018-06-06 07:49:51
这是隐藏在XY problem背后的设计问题。
你已经击落了The Explicit Dependencies Principle
方法和类应该显式地要求(通常通过方法参数或构造函数参数)它们需要的任何协作对象才能正常工作。
public class PrintTask {
private readonly IPrinter printer;
public PrintTask(IPrinter printer) {
this.printer = printer;
}
public void PrintSomething(string text) {
printer.Print(text);
}
}
这将允许依赖类已经注册到容器中
public void ConfigureServices(IServiceCollection services) {
services.AddScoped<IPrinter, Printer>();
services.AddScoped<PrintTask>();
}
从一个灵活的、解耦的类,它的依赖项可以很容易地被模仿和注入。
依赖注入是这里最好的选择,但也有服务定位器反模式,虽然可行,但通常不建议这样做。
https://stackoverflow.com/questions/50707105
复制相似问题