Bit of a newbie question. I am having trouble getting access to dependency injected services from within my own custom class in ASP.NET Core 3.1
I can access services fine from within a controller or razor page e.g. I can get hold of configuration and data context information:
public class DetailModel : PageModel
{
private readonly MyDataContext _context;
private readonly IConfiguration _config;
public DetailModel(MyDataContext context, IConfiguration config)
{
_context = context;
_config = config;
}
etc......
}
I now wish to access these from the constructor of a custom class that is not a controller or razor page. e.g. I am using:
public class ErrorHandling
{
private readonly MyDataContext _context;
private readonly IConfiguration _config;
public ErrorHandling(MyDataContext context, IConfiguration config)
{
_context = context;
_config = config;
}
}
The problem is that when I instantiate my class it insists on me passing the service values into the constructor:
var myErrorHandler = new ErrorHandling(`<wants me to pass context and config values here>`)
This defeats the whole point of DI. I think I am missing something fundamental here!
What am I missing?
ErrorHandlingwith the service collection and resolve it from the built provider. that will inject the desired dependencies