I am trying to inject a repository into an action filter, but getting the following error:
An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type '...ISqlRepository' while attempting to activate '...MyActionFilterAttribute'.
I'm trying to follow Steve Smith's pattern from here. Everything works fine until I add the ISqlRepository reference to the constructor.
Here are the relevant code bits:
Startup.cs
services.AddScoped<MyActionFilterAttribute>();
MyActionFilterAttribute.cs (I realize that I'm implementing IResultFilter here. I'm just trying to stick as close to the example).
public class MyActionFilterAttribute: IResultFilter
{
private ILogger _logger;
private ISqlRepository _sql;
public MyActionFilterAttribute(ILoggerFactory loggerFactory, ISqlRepository sql)
{
_logger = loggerFactory.CreateLogger<LoaderActionFilterAttribute>();
_sql = sql;
}
MyController.cs
[Route("api/[controller]")]
[ServiceFilter(typeof(MyActionFilterAttribute))]
public class MyController: Controller
You need to add ISqlRepository
to your services:
services.AddScoped<ISqlRepository,SqlRepository>();
The reason the sample project referenced did not have to do this is because ILoggerFactory
is added via the framework.