服务提供商为模板用户注册用户管理器时发生例外

时间:2019-04-18 19:32:19

标签: asp.net-mvc

我正在学习ASP .NET Core,今天我偶然发现了一些东西。我有User类,该类继承了IdentityUser并添加了一些自定义字段,例如名字,姓氏等...

User类由其他类型的用户进一步扩展,这些用户最多仅添加一个或两个额外的字段。我决定采用这种方法,因为没有必要在4个地方重复相同的代码。

我已经定义了一个实现接口UserRepository的{​​{1}}。每当我尝试访问IUserRepository<TEntity> where TEntity : User时,都会出现类似以下的异常:

Index

这些是一些代码段:

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[HM.models.users.Medic]' has been registered. Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<T>(IServiceProvider provider) HM.repositories.UserRepository<TEntity>..ctor(ApplicationDbContext context, IServiceProvider serviceProvider, string role) in UserRepository.cs + _userManager = serviceProvider.GetRequiredService<UserManager<TEntity>>(); HM.repositories.MedicRepository..ctor(ApplicationDbContext context, IServiceProvider serviceProvider) in MedicRepository.cs + public MedicRepository(ApplicationDbContext context, IServiceProvider serviceProvider) : base(context, serviceProvider, _role) { } HM.persistence.UnitOfWork..ctor(ApplicationDbContext context, IServiceProvider _serviceProvider) in UnitOfWork.cs + Medics = new MedicRepository(_context, _serviceProvider); app.Controllers.MedicController.Index() in MedicController.cs + using (var unitOfWork = new UnitOfWork(_context, _serviceProvider)) Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments) System.Threading.Tasks.ValueTask<TResult>.get_Result() Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync() Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync() Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync() Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

MedicController

// GET: Medic public async Task<IActionResult> Index() { using (var unitOfWork = new UnitOfWork(_context,_serviceProvider)) { return View(await unitOfWork.Medics.GetAll()); } } UserRepository

IUserRepository

最后,医生:

   public interface IUserRepository<TEntity> where TEntity : User
    {
        Task Add(TEntity user, string password);
        Task Remove(TEntity user);
        Task Update(TEntity user);
        Task<IEnumerable<TEntity>> GetAll();
        Task<TEntity> GetById(string id);
        Task<bool> Any(Func<TEntity, bool> predicate);
    }

    public class UserRepository<TEntity> : IUserRepository<TEntity> where TEntity : User
    {
        private readonly string _role;
        private readonly UserManager<TEntity> _userManager;

        public UserRepository(ApplicationDbContext context, IServiceProvider serviceProvider, string role)
        {
            _role = role;
            _userManager = serviceProvider.GetRequiredService<UserManager<TEntity>>();
        }


        public async Task<IEnumerable<TEntity>> GetAll()
        {
            return await _userManager.GetUsersInRoleAsync(_role);
        }
    }

我已经调试了该应用程序:它将在[Table("Medic")] public class Medic : User { [DisplayName("Departments")] public ICollection<MedicDepartment> departments { get; set; } [DisplayName("Diagnostics")] public ICollection<MedicDiagnostic> diagnostics { get; set; } [PersonalData] [DisplayName("Rank")] [StringLength(30, MinimumLength = 3, ErrorMessage = "The rank name must be between 3 and 30 characters long!")] public string rank { get; set; } } 内的_userManager = serviceProvider.GetRequiredService<UserManager<TEntity>>();处引发此异常。我不明白为什么这种情况会发生 我已经明确说明了UserRepository

谢谢! 附言我删除了一些代码和一些想法,以使此帖子更可重用。 P.S.S:where TEntity : User类扩展了MedicRepository并调用了UserRepository,到目前为止,它什么都没有包含。 base包含所有应用程序存储库,并在其构造函数中的每个存储库上调用UnitOfWork。 P.S.S.S.我想为该存储库使用模板,以避免在控制器内部进行强制转换。它曾经返回与“用户”相关的数据。

1 个答案:

答案 0 :(得分:1)

我知道了。为UserManager<User>注册服务是不够的,但是我还必须为继承UserManager的每种类型的用户注册User

首先,我将这些行添加到Startup.cs内的ConfigureServices中。它使用IdentityCore代替Identity

        services.AddIdentityCore<Medic>()                       //add the derived user type from custom user
            .AddRoles<IdentityRole>()
            .AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<Medic, IdentityRole>>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddDefaultUI();

第二,别忘了添加管理员。与以前相同,在相同的文件和方法中添加:

   services.AddScoped<UserManager<User>, UserManager<User>>();     //the user manager for the base type of User
   services.AddScoped<UserManager<Medic>, UserManager<Medic>>();   //the user manager for Medics

希望有帮助!

相关问题