简体   繁体   English

使用 Net Core 默认 DI 注入字符串和服务

[英]Injecting strings and services with Net Core default DI

I have a Net Core 2.1 Console application where I do something like this:我有一个 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;
    }

In other words, I need to inject services and configuration string in my Worker class in some way.换句话说,我需要以某种方式在我的Worker类中注入服务和配置字符串。

Can someone suggest me the right way to do it?有人可以建议我正确的方法吗?

Just change your DI configuration to the following:只需将您的 DI 配置更改为以下内容:

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

Or as suggested use the IOptions interface to inject your configuration object into the class.或者按照建议使用IOptions接口将您的配置对象注入到类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM