[英]How can I pass an instance of LoggerFactory to ActionFilterAttribute
再會。
我正在嘗試通過在我的自定義 ActionFilterAttribute 類中注入 LoggerFactory 來使用日志記錄,但是在控制器方法之一中使用 Attribute 時,我收到一條錯誤消息
[CS7036] There is no argument given that corresponds to the required formal parameter 'logger' of 'Tracker.Tracker(ILoggerFactory)'
下面是這個類的實現:
using System;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
namespace ImmoSales.Tracking
{
public class Tracker : ActionFilterAttribute
{
public string ActionType { get; set; }
public string ActionName { get; set; }
private readonly ILoggerFactory _logger;
public Tracker(ILoggerFactory logger)
{
_logger = logger;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
}
public override void OnActionExecuted(ActionExecutedContext context)
{
base.OnActionExecuted(context);
}
public override void OnResultExecuting(ResultExecutingContext context)
{
base.OnResultExecuting(context);
}
public override void OnResultExecuted(ResultExecutedContext context)
{
base.OnResultExecuted(context);
}
}
}
當我嘗試在控制器中使用跟蹤器時出現上述錯誤,如下所示:
[Tracker(ActionType="testType", ActionName="testName")]
public IActionResult Index()
{
return View();
}
可以做些什么來修復錯誤?
由於您正在操作過濾器中進行構造函數注入,因此您可以使用ServiceFilter
屬性啟用它,您可以在其中傳遞過濾器的類型
[ServiceFilter(typeof(Tracker))]
public IActionResult Index()
{
// to do : return something
}
確保您已在ConfigureServices
方法中注冊過濾器
services.AddScoped<Tracker>();
如果要將其他參數傳遞給過濾器,可以更新過濾器構造函數以包含這些參數。
public class Tracker : ActionFilterAttribute
{
private string _actionType { get; set; }
private string _actionName { get; set; }
private readonly ILoggerFactory _logger;
public Tracker(ILoggerFactory logger, string actionType, string actionName)
{
this._logger = logger;
this._actionName = actionName;
this._actionType = actionType;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
}
public override void OnActionExecuted(ActionExecutedContext context)
{
base.OnActionExecuted(context);
}
public override void OnResultExecuting(ResultExecutingContext context)
{
base.OnResultExecuting(context);
}
public override void OnResultExecuted(ResultExecutedContext context)
{
base.OnResultExecuted(context);
}
}
並使用TypeFilter
屬性啟用您的過濾器,您可以在其中顯式傳遞參數
[TypeFilter(typeof(Tracker), Arguments = new object[] { "Abc", "Xyz" })]
public IActionResult Index()
{
// to do : return something
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.