abp icon indicating copy to clipboard operation
abp copied to clipboard

Keyed Service Issue in .NET with ABP Framework

Open gabrielschmith opened this issue 2 years ago • 7 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Description

Dear ABP Framework Team,

I hope this message finds you well. I am writing to report a bug that I have encountered while working with the ABP Framework in a .NET environment. Specifically, the issue pertains to the functionality of the Keyed Service.

The Keyed Service in .NET is not functioning as expected when integrated with the ABP Framework. The expected behavior is for the service to correctly resolve dependencies based on the provided key. However, in the current scenario, the service fails to do so, leading to unresolved dependencies and subsequent application errors.

This issue is impacting the application's performance and its ability to dynamically resolve dependencies based on keys, which is a crucial functionality for our project.

I am attaching relevant code snippets and error logs for your reference. It would be greatly appreciated if your team could investigate this issue. I am available for any further information or clarification needed to expedite the resolution of this bug.

Thank you for your attention to this matter, and I look forward to your prompt response.

Reproduction Steps

  1. Set up a .NET project with ABP Framework integration.
  2. Implement a Keyed Service as per the standard .NET guidelines.
  3. Attempt to resolve dependencies using the Keyed Service.
  4. Observe the failure in dependency resolution.

My Exemple:

public class SmsTwilioModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        Configure<SmsTwilioOptions> context.Services.GetConfiguration().GetSection("Sms:Twilio:Sms"));
        
        context.Services.AddKeyedTransient<ISmsSender, SmsTwilioSender>("Sms");
    }
}
public class WhatsAppTwilioModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        Configure<WhatsAppTwilioOptions>(context.Services.GetConfiguration().GetSection("Sms:Twilio:WhatsApp"));
        
        context.Services.AddKeyedTransient<ISmsSender, WhatsAppTwilioSender>("WhatsApp");
    }
}
...
protected override async ValueTask ExecuteAsync(ActivityExecutionContext context)
    {
        var keyedServiceProvider = context.GetRequiredService<IKeyedServiceProvider>();
        var logger = context.GetRequiredService<ILogger<SmsActivity>>();
        
        try
        {
            var sender = keyedServiceProvider.GetRequiredKeyedService<ISmsSender>("Sms");
            var phoneNumber = PhoneNumber.Get(context);
            var body = Body.Get(context);

            logger.LogInformation("Sending SMS with body");
            await sender.SendAsync(phoneNumber, body);
            await context.CompleteActivityWithOutcomesAsync("Success");
        }
        catch (Exception ex)
        {
            logger.LogException(ex);
            await context.CompleteActivityWithOutcomesAsync("Failed", ex.ToString());
        }
    }
...

Error on execute code above:

 An exception was caught from a downstream middleware component
Autofac.Core.Registration.ComponentNotRegisteredException: The requested service 'Microsoft.Extensions.DependencyInjection.IKeyedServiceProvider' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

See https://autofac.rtfd.io/help/service-not-registered for more info.
   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[T](IServiceProvider provider)
   at Elsa.Workflows.WorkflowExecutionContext.GetRequiredService[T]()
   at Elsa.Workflows.ActivityExecutionContext.GetRequiredService[T]()
   at Cencosud.Platform.Notification.Elsa.Host.Activities.Notifications.SmsActivity.ExecuteAsync(ActivityExecutionContext context) in X:\sources\loud\cencosud\Cencosud.Platform.Notification\src\Cencosud.Platform.Notification.Elsa.Host\Activities\Notifications\SmsActivity.cs:line 26
   at Elsa.Workflows.Activity.Elsa.Workflows.Contracts.IActivity.ExecuteAsync(ActivityExecutionContext context)
   at Elsa.Workflows.Middleware.Activities.DefaultActivityInvokerMiddleware.ExecuteActivityAsync(ActivityExecutionContext context)
   at Elsa.Workflows.Runtime.Middleware.Activities.BackgroundActivityCollectorMiddleware.ExecuteActivityAsync(ActivityExecutionContext context)
   at Elsa.Workflows.Middleware.Activities.DefaultActivityInvokerMiddleware.InvokeAsync(ActivityExecutionContext context)
   at Elsa.Workflows.Middleware.Activities.NotificationPublishingMiddleware.InvokeAsync(ActivityExecutionContext context)
   at Elsa.Workflows.Middleware.Activities.ExecutionLogMiddleware.InvokeAsync(ActivityExecutionContext context)
   at Elsa.Workflows.Middleware.Activities.ExceptionHandlingMiddleware.InvokeAsync(ActivityExecutionContext context)

Error on initialization application:

[18:15:02 INF] Starting Elsa.Host
[18:15:24 FTL] Host terminated unexpectedly!
System.InvalidOperationException: This service descriptor is keyed. Your service provider may not support keyed services.
   at Microsoft.Extensions.DependencyInjection.ServiceDescriptor.ThrowKeyedDescriptor()
   at Microsoft.Extensions.DependencyInjection.ServiceDescriptor.get_ImplementationType()
   at Autofac.Extensions.DependencyInjection.AutofacRegistration.Register(ContainerBuilder builder, IServiceCollection services, Object lifetimeScopeTagForSingletons)
   at Autofac.Extensions.DependencyInjection.AutofacRegistration.Populate(ContainerBuilder builder, IServiceCollection services, Object lifetimeScopeTagForSingletons)
   at Autofac.Extensions.DependencyInjection.AutofacRegistration.Populate(ContainerBuilder builder, IServiceCollection services)
   at Volo.Abp.Autofac.AbpAutofacServiceProviderFactory.CreateBuilder(IServiceCollection services)
   at Microsoft.AspNetCore.Builder.ConfigureHostBuilder.ServiceProviderFactoryAdapter`1.CreateBuilder(IServiceCollection services)
   at Microsoft.Extensions.Hosting.HostApplicationBuilder.<>c__DisplayClass30_0`1.<ConfigureContainer>b__0()
   at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()
   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
   at Cencosud.Platform.Notification.Elsa.Host.Program.Main(String[] args) in Program.cs:line 38

Expected behavior

The expected behavior is for the service to correctly resolve dependencies based on the provided key.

Actual behavior

In the current scenario, the service fails to do so, leading to unresolved dependencies and subsequent application errors.

Regression?

No response

Known Workarounds

No response

Version

8.0.1

User Interface

Common (Default)

Database Provider

EF Core (Default)

Tiered or separate authentication server

Separate Auth Server

Operation System

Windows (Default)

Other information

No response

gabrielschmith avatar Jan 06 '24 21:01 gabrielschmith

hi

We have to wait for this https://github.com/autofac/Autofac.Extensions.DependencyInjection/issues/112

maliming avatar Jan 07 '24 01:01 maliming

I'm having this problem too, any workarounds?

AndersChen123 avatar Jan 11 '24 15:01 AndersChen123

No, You have to wait for https://github.com/autofac/Autofac.Extensions.DependencyInjection/issues/112

maliming avatar Jan 12 '24 01:01 maliming

hi

Autofac already support this and will release soon.

https://github.com/autofac/Autofac.Extensions.DependencyInjection/issues/112

maliming avatar Jan 16 '24 02:01 maliming

We fixed this in 8.0, Please wait for the next patch version.

You can add Autofac.Extensions.DependencyInjection 9.0 to your project to fix it as well.

maliming avatar Jan 17 '24 02:01 maliming

We fixed this in 8.0, Please wait for the next patch version.

You can add Autofac.Extensions.DependencyInjection 9.0 to your project to fix it as well.

It doesn't work !

abp new Acme.BookStore -t app-nolayers -csf and add Autofac.Extensions.DependencyInjection 9.0

image

programmer-zheng avatar Jan 17 '24 03:01 programmer-zheng

It seems that we have to add some extra code. Please wait for the next abp 8.0.x version.

maliming avatar Jan 17 '24 03:01 maliming