繁体   English   中英

如何通过ASP.NET Core中的“使用”打开数据库连接?

[英]How to open a database connection through “using” in ASP.NET Core?

我需要访问ActionFilter属性中的数据库上下文。 如何在不将上下文传递给构造函数的情况下做到这一点?

简短的问题是:如何像以前在ASP.NET Framework中一样在一行中获得数据库上下文?

正确的方法是使用依赖项注入来注册过滤器,然后使用ServiceFilterAttribute将过滤器放入管道中。 这样,将使用依赖项注入来解析您的过滤器类型,因此您可以正确注入数据库上下文并像平常一样使用它。

public class MyActionFilter : IActionFilter
{
    private readonly MyDbContext _dbContext;

    public MyActionFilter(MyDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // use _dbContext here
    }

    public void OnActionExecuting(ActionExecutingContext context)
    { }
}

Startup.ConfigureServices注册类型:

services.AddTransient<MyActionFilter>();

然后使用ServiceFilterAttribute激活它。 作为控制器上的属性或动作:

[ServiceFilter(typeof(MyActionFilter))]
public class MyController : Controller
{
    // …
}

或通过MvcOptions像其他任何过滤器一样全局注册它:

services.AddMvc(options => {
    options.Filters.Add(new ServiceFilterAttribute(typeof(MyActionFilter)));
});

然后,将对每个需要过滤器的请求解析MyActionFilter ,并且将从依赖项注入容器中以适当的生存期注入数据库上下文。

通常不建议自己实例化数据库上下文(在单元测试之外)。 您在ASP.NET Core中有一个依赖项注入容器,因此您应该在各处都使用它,而不是自己维护对象生存期和依赖项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM