Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 503
danyolgiax Avatar asked Oct 15 '25 22:10

danyolgiax


1 Answers

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.

like image 195
Jamie Rees Avatar answered Oct 17 '25 11:10

Jamie Rees