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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With