Base solution for your next web application
Open Closed

Dependency Injection issue from Console Application #11214


User avatar
0
adamphones created

I have created a console application which depends on CoreModule.

I have annotated console application module as below:

[DependsOn(typeof(MyCoreModule))] public class MyConsoleAppModule : AbpModule{ }

When the console application is run I get dependency injection error in this line in CoreModule PostInitiliaze method: IocManager.Resolve<ChatUserStateWatcher>().Initialize();

Error message:

``Can't create component 'MyApp.Friendships.Cache.UserFriendsCache' as it has dependencies to be satisfied.

'MyApp.Friendships.Cache.UserFriendsCache' is waiting for the following dependencies:

  • Service 'Abp.Domain.Repositories.IRepository`2[[MyApp.Friendships.Friendship, MyApp.Core, Version=11.4.0.0, Culture=neutral, PublicKeyToken=null],[System.Int64, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' which was not registered.
  • Service 'Abp.Domain.Repositories.IRepository`2[[MyApp.Chat.ChatMessage, MyApp.Core, Version=11.4.0.0, Culture=neutral, PublicKeyToken=null],[System.Int64, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' which was not registered.
  • Service 'Abp.MultiTenancy.TenantCache2[[MyApp.MultiTenancy.Tenant, MyApp.Core, Version=11.4.0.0, Culture=neutral, PublicKeyToken=null],[MyApp.Authorization.Users.User, MyApp.Core, Version=11.4.0.0, Culture=neutral, PublicKeyToken=null]]' which was registered but is also waiting for dependencies. 'Abp.MultiTenancy.TenantCache2[[MyApp.MultiTenancy.Tenant, MyApp.Core, Version=11.4.0.0, Culture=neutral, PublicKeyToken=null],[MyApp.Authorization.Users.User, MyApp.Core, Version=11.4.0.0, Culture=neutral, PublicKeyToken=null]]' is waiting for the following dependencies:
  • Service 'Abp.Domain.Repositories.IRepository`1[[MyApp.MultiTenancy.Tenant, MyApp.Core, Version=11.4.0.0, Culture=neutral, PublicKeyToken=null]]' which was not registered.
  • Service 'MyApp.Authorization.Users.UserStore_07b5c24a-14b4-4126-8563-99bd25a1bc6e' which was registered but is also waiting for dependencies. 'MyApp.Authorization.Users.UserStore_07b5c24a-14b4-4126-8563-99bd25a1bc6e' is waiting for the following dependencies:
  • Service 'Abp.Domain.Repositories.IRepository`2[[MyApp.Authorization.Users.User, MyApp.Core, Version=11.4.0.0, Culture=neutral, PublicKeyToken=null],[System.Int64, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' which was not registered.
  • Service 'Abp.Domain.Repositories.IRepository`2[[Abp.Authorization.Users.UserLogin, Abp.Zero.Common, Version=7.3.0.0, Culture=neutral, PublicKeyToken=null],[System.Int64, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' which was not registered.
  • Service 'Abp.Domain.Repositories.IRepository`2[[Abp.Authorization.Users.UserRole, Abp.Zero.Common, Version=7.3.0.0, Culture=neutral, PublicKeyToken=null],[System.Int64, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' which was not registered.
  • Service 'Abp.Domain.Repositories.IRepository`1[[MyApp.Authorization.Roles.Role, MyApp.Core, Version=11.4.0.0, Culture=neutral, PublicKeyToken=null]]' which was not registered.
  • Service 'Abp.Domain.Repositories.IRepository`2[[Abp.Authorization.Users.UserClaim, Abp.Zero.Common, Version=7.3.0.0, Culture=neutral, PublicKeyToken=null],[System.Int64, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' which was not registered.
  • Service 'Abp.Domain.Repositories.IRepository`2[[Abp.Authorization.Users.UserPermissionSetting, Abp.Zero.Common, Version=7.3.0.0, Culture=neutral, PublicKeyToken=null],[System.Int64, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' which was not registered.
  • Service 'Abp.Domain.Repositories.IRepository`2[[Abp.Authorization.Users.UserOrganizationUnit, Abp.Zero.Common, Version=7.3.0.0, Culture=neutral, PublicKeyToken=null],[System.Int64, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' which was not registered.
  • Service 'Abp.Domain.Repositories.IRepository`2[[Abp.Organizations.OrganizationUnitRole, Abp.Zero.Common, Version=7.3.0.0, Culture=neutral, PublicKeyToken=null],[System.Int64, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' which was not registered.``

Any idea how to resolve this issue?

Thanks


6 Answer(s)
  • User Avatar
    0
    musa.demir created

    Can you please check the implementation of the Migrator project and see if you forget the add some code.

    https://github.com/aspnetzero/aspnet-zero-core/blob/dev/aspnet-core/src/MyCompanyName.AbpZeroTemplate.Migrator/Program.cs https://github.com/aspnetzero/aspnet-zero-core/blob/dev/aspnet-core/src/MyCompanyName.AbpZeroTemplate.Migrator/AbpZeroTemplateMigratorModule.cs

  • User Avatar
    0
    adamphones created

    Hi Musa,

    That's what I did actually. followed the example. I raised another question here how to set up Window Service. What I am trying to do is to move background tasks(jobs) into Windows Service from Application pool. I obvioulsy don't know the order to set this up correctly. The only difference I can see in those two is that Migrator project depends on EntityFramework project where mine is Core project.

    Program.cs :

    IHost host = Host.CreateDefaultBuilder(args) .UseWindowsService(options => { options.ServiceName = ".NET Joke Service"; }) .ConfigureServices(services => { services.AddHostedService&lt;WindowsBackgroundService&gt;(); }) .Build(); await host.RunAsync();

    WindowsBackgroundService.cs: This is where I placed the bootstrapper code.

        ``public class WindowsBackgroundService : BackgroundService
         {
        private readonly ILogger&lt;WindowsBackgroundService&gt; _logger;
    
        public WindowsBackgroundService(ILogger&lt;WindowsBackgroundService&gt; logger)
        {
            _logger = logger;
        }
    
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                using (var bootstrapper = AbpBootstrapper.Create&lt;PricingEngineServiceModule&gt;())
                {
                    bootstrapper.IocManager.IocContainer
                        .AddFacility&lt;LoggingFacility&gt;(f => f.UseAbpLog4Net()
                            .WithConfig("log4net.config")
                        );
    
                    bootstrapper.Initialize();
    
                    
                    while (!stoppingToken.IsCancellationRequested)
                    {
                        _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
    
                        using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable&lt;DataImportJob&gt;())
                        {
                            await migrateExecuter.Object.Execute(null);
                        }
    
                        await Task.Delay(1000, stoppingToken);
                    }
    
                    Console.WriteLine("Press ENTER to exit...");
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "{Message}", ex.Message);
                Environment.Exit(1);
            }
            
        }``
    

    MyModule.cs:

    ` [DependsOn(typeof(CoreModule))] public class EngineServiceModule : AbpModule { private readonly IConfigurationRoot _appConfiguration;

    public EngineServiceModuleCoreModule coreModule)
    {
        _appConfiguration = AppConfigurations.Get(
            typeof(CoreModule).GetAssembly().GetDirectoryPathOrNull(),
            addUserSecrets: true
        );
    }
    
    public override void PreInitialize()
    {
        Configuration.DefaultNameOrConnectionString = _appConfiguration.GetConnectionString(
            MyAppConsts.ConnectionStringName
        );
        Configuration.Modules.AspNetZero().LicenseCode = _appConfiguration["AbpZeroLicenseCode"];
    
        Configuration.BackgroundJobs.IsJobExecutionEnabled = false;
        Configuration.ReplaceService(typeof(IEventBus), () =>
        {
            IocManager.IocContainer.Register(
                Component.For<IEventBus>().Instance(NullEventBus.Instance)
            );
        });
    }
    
    public override void Initialize()
    {
        IocManager.RegisterAssemblyByConvention(typeof(EngineServiceModule).GetAssembly());
        ServiceCollectionRegistrar.Register(IocManager);
    }
    

    }`

    ServiceCollectionRegistrar.cs is the same as Migrator project.

    `public static class ServiceCollectionRegistrar { public static void Register(IIocManager iocManager) { var services = new ServiceCollection();

        IdentityRegistrar.Register(services);
    
        WindsorRegistrationHelper.CreateServiceProvider(iocManager.IocContainer, services);
    }
    

    }`

  • User Avatar
    0
    adamphones created

    The main issue was caused by appsettings.json file. I had to AbpZeroLicenseCode key in the settings.

    But this still throwing a new dependency injection issue as :

    Castle.MicroKernel.ComponentActivator.ComponentActivatorException: ComponentActivator: could not instantiate MyApp.Authorization.Users.UserManager ---> System.Exception: Could not instantiate AdamPhones.Spectrum.Authorization.Users.UserManager. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Castle.MicroKernel.ComponentRegistrationException: Type Microsoft.Extensions.Hosting.IHostEnvironment is abstract. As such, it is not possible to instansiate it as implementation of service 'Microsoft.Extensions.Hosting.IHostEnvironment'. Did you forget to proxy it?

    In .net 6 IHostEnvironment is automatically registered

    Can you please tell us how this service will be registered in Castle dependency injection?

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @adamphones

    Normally, this service must be registered during the module initialization and your console app's module must depened on the module which contains UserManager class. Is it possible to share your final module definition for EngineServiceModule ? Does it depend on your code module ?

  • User Avatar
    0
    adamphones created

    HI @ismail,

    When I use your suggestion here in another ticket the issues really disappeared.

    However, I still want to clarify something: My understanding is that if Module A depends on Module B and Module B depends on Module C then Module A should not add Module C as depency in the module class? Is this right? As Because Module B should take care the dependency. For some reason this doesn't seem to work. Even though my new Module shoud only depend on CoreModule and when I use dependency to only CoreModule I get exceptions that Domain and repositories are not registered. Those dependency issues disappear if I make my new module to depend on EntityFrameWork module. Somehow some registeries in Core like :IocManager.Resolve<ChatUserStateWatcher>().Initialize(); in PostInitialize in core module fails.

    Migrator project also depends on EntityFramework and I guess it is required?

  • User Avatar
    0
    ismcagdas created
    Support Team

    However, I still want to clarify something: My understanding is that if Module A depends on Module B and Module B depends on Module C then Module A should not add Module C as depency in the module class? Is this right?

    Yes, this is right but Module A can still depend on Module C and it shouldn't cause any problems.

    Migrator project also depends on EntityFramework and I guess it is required?

    Yes, this is correct.