【发布时间】:2020-02-03 06:59:03
【问题描述】:
我有一个使用存储库模式的 ASP.NET Core 2.2 MVC Web 应用程序。我创建了一个名为 LogAttribute 的类,它派生自 ActionFilterAttribute,以便在执行控制器操作后记录信息。
这是在 mvc 控制器类中使用此操作过滤器属性的示例:
public class HomeController : Controller
{
private readonly IMyRepository _repository;
public HomeController(IMyRepository repository)
{
_repository = repository;
}
[Log("Go to Home Page")]
public async Task<IActionResult> Index()
{
...
}
[Log("Go to About Page")]
public async Task<IActionResult> About()
{
...
}
}
所以当我转到/Home 时,它应该记录“转到主页”。当我转到/About 页面时,它应该记录“转到关于页面”。
但是,我不知道如何从 LogAttribute 类访问我的存储库。这是LogAttribute 类:
public class LogAttribute : ActionFilterAttribute
{
private IDictionary<string, object> _arguments;
private IMyRepository _repository;
public string Description { get; set; }
public LogAttribute(string description)
{
Description = description;
}
// // Injecting repository as a dependency in the ctor DOESN'T WORK
// public LogAttribute(string description, IMyRepository repository)
// {
// Description = description;
// _repository = repository;
// }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
_arguments = filterContext.ActionArguments;
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var description = Description;
// NullReferenceException since I don't know
// how to access _repository from this class
_repository.AddLog(new LogAction
{
Description = description
});
}
}
所以我的问题是如何从LogAttribute 类访问我的存储库(或至少是我的 DbContext)?
【问题讨论】:
-
@JohnWu - 您提供的链接建议使用可以接收依赖项的公共设置器创建一个属性(即
public ApplicationDbContext Context { get; set; })。但是,我已经尝试过了,但它仍然给我NullReferenceException: Object reference not set to an instance of an object错误,因为 Context 为空。 -
@Dai - 我正在使用 ASP.NET Core 2.2 (
Microsoft.AspNetCore.*)。我已经在我的问题中提到了这一点。 -
@JohnWu 链接到的 QA 是针对非核心 ASP.NET MVC - 虽然令人困惑的是,一些已发布的答案确实适用于 ASP.NET Core。
-
是的,该链接建议适用于 ASP.NET 4.x MVC 应用程序,但不适用于 ASP.NET Core。
标签: c# asp.net-core asp.net-core-2.2