美文网首页
Ioc获取RoleManager失败问题

Ioc获取RoleManager失败问题

作者: Figo_OU | 来源:发表于2018-06-28 17:00 被阅读32次

    自从更新了.net code2.1框架,Microsoft.AspNetCore.All框架也升级了。我的UserManager、RoleManager都获取不了啦。

    我的依赖注入是这样实现的:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    ...
      Ioc.Instance = app.ApplicationServices;
       Ioc.Get<UserManager>();//类似这样
    }
    

    可是一取依赖就报错。错误信息如下:

    InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.SignInManager 1[Authorization.IdentityModels.ApplicationUser]' has been registered.
    

    stackoverflow
    根据stackoverflow的解析,要添加

    services.AddScoped<SignInManager<ApplicationUser>
    , SignInManager<ApplicationUser>>();
    

    可是添加完还是报错。

    原因:
    services.AddIdentity<>( );的这个方法里面就实现了注入

    services.TryAddScoped<UserManager<TUser>, AspNetUserManager<TUser>>();
    services.TryAddScoped<SignInManager<TUser>, SignInManager<TUser>>();
    services.TryAddScoped<RoleManager<TRole>, AspNetRoleManager<TRole>>();
    

    但这个注入的生命周期是在请求的时候才会有的。所以我们直接app.ApplicationServices.Get<>()这种方法去取依赖是不可取的。因为这种方式取出来的只能是TryAddSingleton、AddTransient注入的依赖。

    那么既然如此,直接以TryAddSingleton的方式注入不就好了么?于是我做了以下尝试:

    services.TryAddSingleton<RoleManager<MongoIdentityRole>, AspNetRoleManager<MongoIdentityRole>>();
    services.TryAddSingleton<UserManager<MongoIdentityUser>, AspNetUserManager<MongoIdentityUser>>();
    

    结果所有的请求都失败了,直接返回500.

    最后的解决办法是:
    在请求过来的地方,通过上下文去获取

    var roleManager = context.HttpContext.RequestServices.GetService<RoleManager<MongoIdentityRole>>();
    

    相关文章

      网友评论

          本文标题:Ioc获取RoleManager失败问题

          本文链接:https://www.haomeiwen.com/subject/uhlgyftx.html