How to open a database connection through "using" in ASP.NET Core?

时间:2017-12-18 08:16:26

标签: c# asp.net-core

I need access to database context inside my with open("Test.txt","r") as test_file: for line in test_file: if line.endswith(';\n'): print(line) attribute. How can I do that without passing the context through the constructor?

The short question is: How to get the database context in one line as we did in the ASP.NET Framework before?

1 个答案:

答案 0 :(得分:5)

正确的方法是使用依赖注入注册过滤器,然后使用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中有一个依赖注入容器,所以你应该在任何地方使用它而不是自己维护对象的生命周期和依赖关系。