zoukankan      html  css  js  c++  java
  • asp.net core mvc 在中间件中使用依赖注入问题:System.InvalidOperationException: Cannot resolve scoped service 'IXXXService' from root provider.

    今天在弄JWT的时候需要用到用户验证使用一个自己写好的验证,但在出现了:System.InvalidOperationException: Cannot resolve scoped service 'IXXXService' from root provider.

    说的是被释放掉了:

    Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

    直接上解决方法:

    1、注册你的服务

    public void ConfigureServices(IServiceCollection services)
    {
      /* 注册服务 AddServices注册了IUsersService*/
      services.AddServices();
    }

    2、定义中间件和入口

    public static class TokenProviderExtensions
        {
            public static IApplicationBuilder UseAuthentication(this IApplicationBuilder app, TokenProviderOptions options)
            {
                if (app == null)
                {
                    throw new ArgumentNullException(nameof(app));
                }
                return app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options));
            }
        }
    //TokenProviderMiddleware 里面的 Invoke 里面去用就没问题了

    public
    async Task Invoke(HttpContext context, IUsersService usersService) { /* usersService 可以用了 */ await _next(context); }

    3、

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        /*上面扩展的 UseAuthentication */ 
    app.UseAuthentication();
    }

    看了文档大概用是这个意思:

    中间件在构造器中必须是singleton-lifetime.

    如果接受Invoke就可以是singleton-lifetime or
    scoped-lifetime.

  • 相关阅读:
    fastjson把对象转化成json string时避免$ref
    Java 生成UUID
    eclipse创建springboot项目,maven打包时没有将配置文件加入打包文件中处理
    pycharm IDE使用心得
    (16)-Python3之--集合(set)操作
    2021每天一个知识点(一月)
    解决Nginx出现403 forbidden (13: Permission denied)报错的四种方法
    Jmeter函数助手大全
    JMeter去掉启动的cmd命令窗口和制作快捷方式
    Python+Selenium+Unittest实现PO模式web自动化框架(8)
  • 原文地址:https://www.cnblogs.com/huangyoum/p/7802352.html
Copyright © 2011-2022 走看看