c# - 使用 Net Core 默认 DI 注入(inject)字符串和服务

标签 c# dependency-injection

我有一个 Net Core 2.1 控制台应用程序,我在其中执行如下操作:

class Program
{
    static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", false)
            .Build();

        var fullPath = configuration.GetValue<string>("tempPath:fullPath");

        serviceCollection.AddTransient<MyService>();
        serviceCollection.AddTransient<Worker>();
        ...


public class Worker
{
    public string FullPath {get; set;}
    private readonly MyService _myService;

    public Worker(MyService myService,
        string fullpath)
    {
        _myService = myService;
        FullPath=fullpath;
    }

换句话说,我需要以某种方式在我的 Worker 类中注入(inject)服务和配置字符串。

有人可以建议我正确的方法吗?

最佳答案

只需将您的 DI 配置更改为以下内容:

var fullPath = configuration.GetValue<string>("tempPath:fullPath");
serviceCollection.AddTransient<MyService>();
serviceCollection.AddTransient<Worker>(x => new Worker(x.GetRequiredService<MyService>(), fullPath));

或者按照建议使用IOptions 接口(interface)将您的配置对象注入(inject)到类中。

关于c# - 使用 Net Core 默认 DI 注入(inject)字符串和服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59068820/

相关文章:

c# - 如何让 Windows 窗体应用程序与类(class)一起工作?

c# - 如何访问 Windows 8.1 商店应用程序中子部分内的控件?在可视化树中搜索不起作用

entity-framework - Unity Lifetime Managers & EF Data Context --> 最佳实践

c# - 在 Simple Injector 中使用运行时数据获取实例

c# - 当鼠标经过标签并随后恢复正常时,如何使标签变粗

c# - 使用秒表测量抽象方法运行时间

javascript - 为什么 Angular JS 中的依赖注入(inject)比手动管理依赖更好?

javascript - 如何管理不同的 Angular 模块依赖关系

c# - 从 Java 迁移到 C#

java - Java 中使用依赖注入(inject)进行对象初始化