简体   繁体   English

我可以在 ASP.NET Core 的中间件期间访问数据库吗?

[英]Can I access a database during middleware in ASP.NET Core?

I want to create Visitor page我想创建访客页面

private readonly DBDatacontext _db;
private RequestDelegate _requestDelegate;

public VisitorMiddleWare(RequestDelegate requestDelegate, DBDatacontext db)
{
    _requestDelegate = requestDelegate;
    _db = db;
}

public async Task InvokeAsync(HttpContext context)
{
    string visitorId = context.Request.Cookies["VisitorId"];
    string remoteIpAddress = context.Connection.RemoteIpAddress.ToString();

    if (visitorId == null)
    {
        context.Response.Cookies.Append("VisitorId", Guid.NewGuid().ToString(), new 
                  CookieOptions()
            {
                Path = "/",
                HttpOnly = true,
                Secure = false,
            });

        visitorId = context.Request.Cookies["VisitorId"];

        var model = new Visitor()
            {
                Ip = remoteIpAddress
            };

        _db.AddAsync(model);
        _db.SaveChangesAsync();
    }

    await _requestDelegate(context);
}

and in the startup并在启动

app.UseMiddleware(typeof(VisitorMidlleWare));

but I get this error:但我收到此错误:

Cannot resolve scoped service 'DBDatacontext' from root provider.无法从根提供程序解析范围服务“DBDatacontext”。

Your DB context is not a singleton so you should not resolve it in the constructor.您的数据库上下文不是单例,因此您不应在构造函数中解析它。 You can add it instead as a parameter for InvokeAsync:您可以将其添加为 InvokeAsync 的参数:

public async Task InvokeAsync(HttpContext context, DBDatacontext db)
{
}

By default an EF DB context is registered as Scoped, which by default means one is created per request.默认情况下,EF DB 上下文注册为 Scoped,默认情况下,每个请求都会创建一个上下文。 And you cannot make it a singleton because it is not thread-safe.你不能让它成为单例,因为它不是线程安全的。

InvokeAsync can specify other parameters to get scoped and transient dependencies from the service collection. InvokeAsync 可以指定其他参数以从服务集合中获取范围和瞬态依赖项。 You can alternatively access the RequestServices property on the HttpContext to get services dynamically.您也可以访问 HttpContext 上的 RequestServices 属性以动态获取服务。

More on this and more on my blog ;) https://joonasw.net/view/aspnet-core-di-deep-dive更多关于这个和更多关于我的博客;) https://joonasw.net/view/aspnet-core-di-deep-dive

Use cases for each approach:每种方法的用例:

Constructor: Singleton components that are needed for all requests构造函数:所有请求都需要的单例组件

Invoke parameter: Scoped and transient components that are always necessary on requests Invoke 参数:请求中始终需要的作用域和瞬态组件

RequestServices: Components that may or may not be needed based on runtime information RequestServices:根据运行时信息可能需要或不需要的组件

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

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