简体   繁体   中英

Injecting strings and services with Net Core default DI

I have a Net Core 2.1 Console application where I do something like this:

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.

Can someone suggest me the right way to do it?

Just change your DI configuration to the following:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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