Home > Back-end >  Dependency injection when instantiating a new class
Dependency injection when instantiating a new class

Time:08-30

pretty new to C# and I'm having trouble figuring out how to get dependency injection to work when instantiating a new class.

I have an Error class that I use to store basic information about Errors, warnings, etc when using quartz to pass to the UI when something happens with the job. We also want to use the seri log inside those errors to log in case something happens.

How would I use dependency injection with my Error class to use ILogger ( seiri log) when creating a new Error class.

The JobClass that we use has DI with the ILogger. ( I don't know if this matters)

When I do Error e = new Error(); it wants me to pass the ILogger as parameter.

Thanks

CodePudding user response:

When I do Error e = new Error(); it wants me to pass the ILogger as parameter.

Well, yeah, you're trying to call a constructor directly, it has to be correct C# code. Dependency injection is at the framework level, not the language level.

With that in mind, if you want to construct an object with DI, you have to ask your framework to construct it for you, with something similar to:

var error = services.GetRequiredService<IError>();

And have your error class implement that interface and register it as a transient dependency (ie, get a new one every call).

I want to stress however that you shouldn't be doing this, DI spreads virally for you. If you want one of these things created for you, simply add an IError parameter to your controller constructor and you'll get sent one on object creation to do whatever you want with it.

  • Related