首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从Startup中配置的容器解析类库中的依赖项?

如何从Startup中配置的容器解析类库中的依赖项?
EN

Stack Overflow用户
提问于 2018-06-06 02:53:26
回答 1查看 1.3K关注 0票数 0

目标是使用IoC并能够模拟单元测试的依赖项。

项目:具有多个类库的.NET Core Web API

我在我的IoC上使用Microsoft.Extensions.DependencyInjection,如果它支持我想要实现的功能,我想继续使用它。

问题:我的程序集中(类库)中至少有一个类有一个需要模拟的依赖项(例如,使用Moq)。我完全理解我可以使用构造函数注入来注入接口,但这并不适合这个场景。

我只是想在我的程序集中完成的工作就是使用我在Web API的Startup类中启动的容器来解析依赖项。

我该怎么做呢?如果这是不可能的,什么可能是另一种方法来完成相同的事情,即模拟我的打印机而不使用依赖注入?

下面是一些示例代码,希望能澄清这一点。

Web API的Startup.cs (引用了定义打印机的程序集)

代码语言:javascript
复制
public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IPrinter, Printer>();
}

在一个不同的程序集中,我想解析一个使用相同容器的Printer实例。

代码语言:javascript
复制
    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);
        }
    }
EN

回答 1

Stack Overflow用户

发布于 2018-06-06 07:49:51

这是隐藏在XY problem背后的设计问题。

你已经击落了The Explicit Dependencies Principle

方法和类应该显式地要求(通常通过方法参数或构造函数参数)它们需要的任何协作对象才能正常工作。

代码语言:javascript
复制
public class PrintTask {
    private readonly IPrinter printer;

    public PrintTask(IPrinter printer) {
        this.printer = printer;
    }

    public void PrintSomething(string text) {
        printer.Print(text);
    }
}

这将允许依赖类已经注册到容器中

代码语言:javascript
复制
public void ConfigureServices(IServiceCollection services) {
    services.AddScoped<IPrinter, Printer>();
    services.AddScoped<PrintTask>();
}

从一个灵活的、解耦的类,它的依赖项可以很容易地被模仿和注入。

依赖注入是这里最好的选择,但也有服务定位器反模式,虽然可行,但通常不建议这样做。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50707105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档