天天看點

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.