Open Closed

Not able to create user in MicroService Architecture #1069


User avatar
0
lalitChougule created

Check the docs before asking a question: https://docs.abp.io/en/commercial/latest/ Check the samples, to see the basic tasks: https://docs.abp.io/en/commercial/latest/samples/index The exact solution to your question may have been answered before, please use the search on the homepage.

  • ABP Framework version: <span class="colour" style="color:rgb(85, 85, 85)">v3.0.4</span>
  • UI type: Angular
  • DB provider: EF Core
  • Tiered (MVC) or Identity Server Separated (Angular): no / yes
  • Exception message and stack trace: N.A
  • Steps to reproduce the issue: N.A

This my Microservice folder structure

Gateway
	MainProject.HttpApi.Host
Microservices
	ProjectA.HttpApi.Host
	ProjectB.HttpApi.Host
	ProjectC.HttpApi.Host -- IdentityServer
	ProjectD.HttpApi.Host
Module
	ProjectA
		scr
			ProjectA.Application
			ProjectA.Application.Contracts
			ProjectA.Domain
			ProjectA.Domain.Shared
			ProjectA.EntityFrameworkCore
			ProjectA.HttpApi
			ProjectA.HttpApiClient
		test
			ProjectA.Application.Tests
			ProjectA.Domain.Tests
			ProjectA.EntityFrameworkCore.Tests
			ProjectA.HttpApiClient.ConsoleTestApp
			ProjectA.TestBase
	ProjectB
		src
			ProjectB.Application
			ProjectB.Application.Contracts
			ProjectB.Domain
			ProjectB.Domain.Shared
			ProjectB.EntityFrameworkCore
			ProjectB.HttpApi
			ProjectB.HttpApiClient
		test
			ProjectB.Application.Tests
			ProjectB.Domain.Tests
			ProjectB.EntityFrameworkCore.Tests
			ProjectB.HttpApiClient.ConsoleTestApp
			ProjectB.TestBase
	ProjectC
		src
			ProjectC.Application
			ProjectC.Application.Contracts
			ProjectC.Domain
			ProjectC.Domain.Shared
			ProjectC.EntityFrameworkCore
			ProjectC.HttpApi
			ProjectC.HttpApiClient
		test
			ProjectC.Application.Tests
			ProjectC.Domain.Tests
			ProjectC.EntityFrameworkCore.Tests
			ProjectC.HttpApiClient.ConsoleTestApp
			ProjectC.TestBase
	ProjectD
		src
			ProjectD.Application
			ProjectD.Application.Contracts
			ProjectD.Domain
			ProjectD.Domain.Shared
			ProjectD.EntityFrameworkCore
			ProjectD.HttpApi
			ProjectD.HttpApiClient
		test
			ProjectD.Application.Tests
			ProjectD.Domain.Tests
			ProjectD.EntityFrameworkCore.Tests
			ProjectD.HttpApiClient.ConsoleTestApp
			ProjectD.TestBase

I want to create user in Project B ApplicationService by using IdentityUserManager. I am not able to access IdentityUserManager in Project B Am I missing anything with reference ?


12 Answer(s)
  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    You need to add references of:

    • Identity.HttpApi
    • Identity.EntityFrameworkCore
    • Identity.Application

    packages. Also I would suggest checking out microservice template docs.

  • User Avatar
    0
    lalitChougule created

    Thank you @gterdem !!!

  • User Avatar
    0
    lalitChougule created

    Hi

    I installed these packages from nuget manager as below

    • <PackageReference Include="Identity.EntityFrameworkCore" Version="1.2.7" />
    • <PackageReference Include="Volo.Abp.Auditing" Version="3.0.4" />
    • <PackageReference Include="Volo.Abp.AuditLogging.Domain" Version="3.0.4" />

    My AppService.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.Extensions.Localization;
    using Volo.Abp;
    using Volo.Abp.Application.Dtos;
    using Volo.Abp.Identity;
    
    public class SupplierRegistrationAppService : ProfileManagementAppService, ISupplierRegistrationAppService
    {
    	private readonly IdentityUserManager _identityUserManager;
        private readonly IIdentityRoleRepository _identityRoleRepository;
    	
    	public SupplierRegistrationAppService(
    		IdentityUserManager identityUserManager,
    		IIdentityRoleRepository identityRoleRepository
    		)
    	{
    		_identityUserManager = identityUserManager;
    		_identityRoleRepository = identityRoleRepository;
    	}
    		
    	public async Task<LitmusUserOutputDto> CreateUserAsync(LitmusUserCreateDto input)
    	{
    		var output = new LitmusUserOutputDto();
    		if (input.TenantId.HasValue)
    		{
    			using (CurrentTenant.Change(input.TenantId))
    			{
    				//User
    				var user = new Volo.Abp.Identity.IdentityUser(GuidGenerator.Create(), input.UserName, input.EmailAddress, CurrentTenant.Id);
    				(await _identityUserManager.CreateAsync(user, input.Password)).CheckErrors();
    				await _identityUserManager.SetEmailAsync(user, input.EmailAddress);
    				user.Name = input.FirstName;
    				user.Surname = input.LastName;
    
    				//Role
    				IEnumerable<string> rolesIEnum = await GetRoleNames(input.RoleName);
    				await _identityUserManager.SetRolesAsync(user, rolesIEnum);
    
    				//Output
    				output.EmailId = user.Email;
    				output.Password = input.Password;
    				output.UserId = user.Id;
    
    			}
    		}
    		else
    			throw new Exception("Tenant Id cannot be empty in CreateAsync()");
    
    		return output;
    	}
    
    	private async Task<IEnumerable<string>> GetRoleNames(string RoleName)
    	{
    		var roles = await _identityRoleRepository.GetListAsync();
    		var role = roles.Where(x => x.Name.Equals(RoleName)).FirstOrDefault();
    		var rolesList = new List<string>() { role.Name };
    		IEnumerable<string> rolesIEnum = rolesList;
    		return rolesIEnum;
    	}
    }
    

    My Controller.cs

    using System;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Volo.Abp;
    using Volo.Abp.Application.Dtos;
    
    namespace SCV.Litmus.ProfileManagement.SupplierRegistrations
    {
        [RemoteService]
        [Route("profile/api/ProfileManagement")]
        public class SupplierRegistrationController : ProfileManagementController, ISupplierRegistrationAppService
        {
            private readonly ISupplierRegistrationAppService _SupplierRegistrationAppService;
    
            public SupplierRegistrationController(ISupplierRegistrationAppService SupplierRegistrationAppService)
            {
                _SupplierRegistrationAppService = SupplierRegistrationAppService;
            }
    
            [HttpPost]
            [Route("createUser")]
            public virtual Task<LitmusUserOutputDto> CreateUserAsync(LitmusUserCreateDto input)
            {
                return _SupplierRegistrationAppService.CreateUserAsync(input);
            }
        }
    }
    

    I was able to get references, but now executing this method I am getting the below error :

    2021-03-22 16:31:36.999 +05:30 [ERR] An exception was thrown while activating SCV.Litmus.ProfileManagement.SupplierRegistrations.SupplierRegistrationController -> SCV.Litmus.ProfileManagement.SupplierRegistrations.SupplierRegistrationAppService.
    Autofac.Core.DependencyResolutionException: An exception was thrown while activating SCV.Litmus.ProfileManagement.SupplierRegistrations.SupplierRegistrationController -> SCV.Litmus.ProfileManagement.SupplierRegistrations.SupplierRegistrationAppService.
     ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'SCV.Litmus.ProfileManagement.SupplierRegistrations.SupplierRegistrationAppService' can be invoked with the available services and parameters:
    Cannot resolve parameter 'Volo.Abp.Identity.IdentityUserManager identityUserManager' of constructor 'Void .ctor(SCV.Litmus.ProfileManagement.SupplierRegistrations.ISupplierRegistrationRepository, SCV.Litmus.ProfileManagement.Suppliers.ISupplierRepository, SCV.Litmus.ProfileManagement.Suppliers.ISupplierCodeRepository, SCV.Litmus.ProfileManagement.BusinessEntities.IBusinessEntityRepository, SCV.Litmus.ProfileManagement.SupplierUserProfiles.ISupplierUserProfileRepository, SCV.Litmus.ProfileManagement.SharedServices.ISharedAppService, Volo.Abp.Identity.IdentityUserManager, Volo.Abp.Identity.IIdentityRoleRepository)'.
       at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(ConstructorInfo[] availableConstructors, IComponentContext context, IEnumerable`1 parameters)
       at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
       at Autofac.Core.Resolving.InstanceLookup.CreateInstance(IEnumerable`1 parameters)
       --- End of inner exception stack trace ---
       at Autofac.Core.Resolving.InstanceLookup.CreateInstance(IEnumerable`1 parameters)
       at Autofac.Core.Resolving.InstanceLookup.Execute()
       at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request)
       at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(ResolveRequest request)
       at Autofac.Core.Resolving.ResolveOperation.Execute(ResolveRequest request)
       at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(ResolveRequest request)
       at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
       at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
       at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Type serviceType, IEnumerable`1 parameters)
       at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Type serviceType)
       at Autofac.Extensions.DependencyInjection.AutofacServiceProvider.GetRequiredService(Type serviceType)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
       at Microsoft.AspNetCore.Mvc.Controllers.ServiceBasedControllerActivator.Create(ControllerContext actionContext)
       at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.&lt;&gt;c__DisplayClass5_0.&lt;CreateControllerFactory&gt;g__CreateController|0(ControllerContext controllerContext)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
    --- End of stack trace from previous location where exception was thrown ---
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeNextExceptionFilterAsync&gt;g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
    2021-03-22 16:31:37.043 +05:30 [ERR] ---------- Exception Data ----------
    2021-03-22 16:31:37.044 +05:30 [ERR] ActivatorChain = SCV.Litmus.ProfileManagement.SupplierRegistrations.SupplierRegistrationController -> SCV.Litmus.ProfileManagement.SupplierRegistrations.SupplierRegistrationAppService
    
  • User Avatar
    0
    gterdem created
    Senior .NET Developer
  • User Avatar
    0
    lalitChougule created

    Hi @gterdem ,

    Sorry my bad, copy paste issue.

    These are the packages

    1. <PackageReference Include="Volo.Abp.Identity.Application" Version="3.0.4" />
    2. <PackageReference Include="Volo.Abp.Identity.EntityFrameworkCore" Version="3.0.4" />
    3. <PackageReference Include="Volo.Abp.Identity.HttpApi" Version="3.0.4" />

    Still facing same issues

  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    Did you also add Module Dependencies to your module?

    • typeof(AbpIdentityHttpApiModule)
    • typeof(AbpIdentityEntityFrameworkCoreModule)
    • typeof(AbpIdentityApplicationModule)
  • User Avatar
    0
    lalitChougule created

    @gterdem

    Yup only Module Dependencies part was missing, once I added those dependencies it worked. Thanks alot !!! Appreciate your quick response.

  • User Avatar
    0
    lalitChougule created

    Hi,

    If you go through all the above mentioned issue, I was finally able to create users in Project B. But now in Project B all unit test cases are failing and all have the same error as below :

    Message: 
        Volo.Abp.AbpInitializationException : An error occurred during the initialize Volo.Abp.Modularity.OnApplicationInitializationModuleLifecycleContributor phase of the module Volo.Abp.AspNetCore.Mvc.AbpAspNetCoreMvcModule, Volo.Abp.AspNetCore.Mvc, Version=3.0.4.0, Culture=neutral, PublicKeyToken=null: Could not find singleton service: Microsoft.AspNetCore.Hosting.IWebHostEnvironment, Microsoft.AspNetCore.Hosting.Abstractions, Version=3.1.12.0, Culture=neutral, PublicKeyToken=adb9793829ddae60. See the inner exception for details.
        ---- System.InvalidOperationException : Could not find singleton service: Microsoft.AspNetCore.Hosting.IWebHostEnvironment, Microsoft.AspNetCore.Hosting.Abstractions, Version=3.1.12.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
      Stack Trace: 
        ModuleManager.InitializeModules(ApplicationInitializationContext context)
        AbpApplicationBase.InitializeModules()
        AbpApplicationWithExternalServiceProvider.Initialize(IServiceProvider serviceProvider)
        AbpIntegratedTest`1.ctor()
        ProfileManagementTestBase`1.ctor()
        ProfileManagementApplicationTestBase.ctor()
        XYZAppServiceTests.ctor() line 12
        ----- Inner Stack Trace -----
        ServiceCollectionCommonExtensions.GetSingletonInstance[T](IServiceCollection services)
        AbpAspNetCoreServiceCollectionExtensions.GetHostingEnvironment(IServiceCollection services)
        <>c__DisplayClass1_0.<ConfigureServices>b__2(AbpAspNetCoreMvcOptions options)
        PostConfigureOptions`1.PostConfigure(String name, TOptions options)
        OptionsFactory`1.Create(String name)
        <>c__DisplayClass5_0.<Get>b__0()
        Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
        Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
        Lazy`1.CreateValue()
        Lazy`1.get_Value()
        OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)
        OptionsManager`1.Get(String name)
        OptionsManager`1.get_Value()
        AbpAspNetCoreMvcModule.AddApplicationParts(ApplicationInitializationContext context)
        AbpAspNetCoreMvcModule.OnApplicationInitialization(ApplicationInitializationContext context)
        OnApplicationInitializationModuleLifecycleContributor.Initialize(ApplicationInitializationContext context, IAbpModule module)
        ModuleManager.InitializeModules(ApplicationInitializationContext context)
    

    Sorry to reopen the ticket, but to understand the issue I thought It would be better to mention it here itself.

  • User Avatar
    0
    alper created
    Support Team Director

    this sounds like you need to mock the IWebHostEnvironment in your test module. I'll show you how to do that; https://support.abp.io/QA/Questions/1077/Testing-Overridden-AppService#answer-1bbd38f2-5f8c-36ad-6eeb-39fb70a23930

  • User Avatar
    0
    lalitChougule created

    Hi @alpher,

    I tried implementing your solution but now I am facing the below issue : SQLite Error 1: 'no such table: AbpUsers'.

  • User Avatar
    0
    alper created
    Support Team Director

    I think the major issue has been resolved. can you create a new issue for your new problem.

  • User Avatar
    0
    ServiceBot created
    Support Team Automatic process manager

    This question has been automatically marked as stale because it has not had recent activity.

Made with ❤️ on ABP v9.1.0-preview. Updated on November 19, 2024, 12:56