I have a few functions I use in multiple controllers. I put the functions in a class so that I can use them without duplicating.
When I try to inject my DB context in the class like I do with my controllers I get:
InvalidOperationException: Unable to resolve service for type ‘TMS.Functions.Tools’ while attempting to activate ‘TMS.Controllers.TestController’.
Example of how I inject in my controllers, and what fails in my class:
private readonly TMSContext _context;
public Tools(TMSContext context)
{
_context = context;
}
This is how I inject my tools function:
using TMS.Functions;
namespace TMS.Controllers
{
[Authorize]
public class PayPortalController : Controller
{
private readonly UserManager<TMSUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly TMSContext _context;
private readonly IConfiguration _config;
private readonly Tools _tools;
public PayPortalController(UserManager<TMSUser> userManager
,RoleManager<IdentityRole> roleManager
,TMSContext context
,IConfiguration config
,Tools tools)
{
_userManager = userManager;
_roleManager = roleManager;
_context = context;
_config = config;
_tools = tools;
}
...
What is the proper way to do this for a class?
Thanks!
>Solution :
This error is shown when you haven’t registered a class in Dependency Injection. A good answer to this error can be found here: Dependency Injection error: Unable to resolve service for type while attempting to activate, while class is registered
You will have to register this class in the startup of your web app (in the Program.cs file for dotnet 6).
You can see how to register services in asp.net here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-6.0.
It will look something like this:
builder.Services.AddScoped<IMyDependency, MyDependency>();
I would suggest setting up an interface for the Tools class and then you would register it like so:
builder.Services.AddScoped<ITools, Tools>();
Or without the interface it would look like:
builder.Services.AddScoped<Tools>();
You can use scoped, transient or singleton, depending on how long you want the service available. You can read about this here: AddTransient, AddScoped and AddSingleton Services Differences
