question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to resolve service for type 'System.Func`1[Sentry.IHub] when adding app.UseSentryTracing() and running as AWS Lambda

See original GitHub issue

Please mark the type framework used:

  • [ X ] ASP.NET Core

Please mark the type of the runtime used:

  • [ X ] .NET Core
  • Version: 6.0

Please mark the NuGet packages used:

  • [ X ] Sentry.AspNetCore
  • Version: 3.19.0

Create am AWS Lambda ASP.NET Core Web API Project (https://github.com/aws/aws-lambda-dotnet - Lambda ASP.NET Core Web API - serverless.AspNetCoreWebAPI). This will provide you with two files, LocalEntryPoint (when the project runs locally), and LambdaEntryPoint (when deployed as lambda).

Everything works fine when running the Web API locally (LocalEntryPoint) but throws the below exception when running in lambda environment. System.InvalidOperationException: Unable to resolve service for type 'System.Func`1[Sentry.IHub]' while attempting to activate 'Sentry.AspNetCore.SentryTracingMiddleware'.

With a little research I found out it’s the addition I did in Startup.cs Configure method with app.UseSentryTracing(); per documentation (https://docs.sentry.io/platforms/dotnet/guides/aspnetcore/). SentryTracingMiddleware will request IHub with a Func<IHub> ctor argument which seems like a factory and not sure where to dig into finding more about it (I guess you guys add this dependency in some IServiceCollection extension.

Running the project locally I can confirm that IHub is registered in IServiceCollection.

How I enable Sentry.

public static class WebHostBuilderExtensions
    {
        public static IWebHostBuilder UseSentryIfNotEightDevelopment(
            this IWebHostBuilder webHostBuilder,
            Action<SentryAspNetCoreOptions> sentryOptionsAction = null)
        {
            var isEnabled = SentrySdk.IsEnabled;
            if (!isEnabled)
            {
                var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                var isDevelopment = environment is 
                    EightEnvironment.Dev or 
                    EightEnvironment.Test or 
                    EightEnvironment.QA;

                if (!isDevelopment)
                {
                    webHostBuilder.UseSentry(options => ConfigureSentryOptions(options, sentryOptionsAction));
                }
            }

            return webHostBuilder;
        }
        
        private static void ConfigureSentryOptions(SentryAspNetCoreOptions options, Action<SentryAspNetCoreOptions> sentryOptionsAction = null)
        {
            var isEnabled = SentrySdk.IsEnabled;
            if (!isEnabled)
            {
                if (sentryOptionsAction.IsNotNull())
                {
                    sentryOptionsAction(options);
                }
            }
        }
    }

And using the extension in LambdaEntryPoint.

public class LambdaEntryPoint :
        // When using an ELB's Application Load Balancer as the event source change 
        // the base class to Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction
        Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
    {
        /// <summary>
        /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class
        /// needs to be configured in this method using the UseStartup<>() method.
        /// </summary>
        /// <param name="builder"></param>
        protected override void Init(IWebHostBuilder builder)
        {
            builder
                .UseDefaultServiceProvider(options => options.ValidateScopes = false)
                .UseSentryIfNotEightDevelopment(ConfigureSentryOptions) 
                .UseStartup<Startup>();
        }

        private static void ConfigureSentryOptions(SentryAspNetCoreOptions options)
        {
            options.Release = typeof(LambdaEntryPoint).GetTypeInfo().Assembly.GetName().Version?.ToString();
        }
    }
public void Configure(
            IApplicationBuilder app,
            IUsersAppSettings appSettings,
            IConfiguration configuration)
        {
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor |
                                   ForwardedHeaders.XForwardedProto
            });

            if (!HostingEnvironment.IsEightDevelopment())
            {
                app.UseHsts();
                app.UseHttpsRedirection();
            }

            app.UseExceptionHandlerMiddleware();
            app.UseCancellationTokenRequestLinkTimeoutMiddleware();

            app.UseSwaggerDocuments();

            app.UseRouting();
            if (SentrySdk.IsEnabled)
            {
                app.UseSentryTracing(); // Change
            }
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseCors();
            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
mattjohnsonpintcommented, Jul 6, 2022

I attempted to reproduce the problem and everything appeared to work correctly without error, using either the exact code you provided, or a simplified form.

The only way I was able to get it to error is if the call to webHostBuilder.UseSentry was omitted. In that case, the call to app.UseSentryTracing will indeed give an error response, with the exception message you mentioned showing in the AWS CloudWatch logs.

You might take another look at your isDevelopment check, since you’re using that to decide whether to call UseSentry. Perhaps the environment variable is not what you think it is.

Either way, I’d remove the SentrySdk.IsEnabled test in all locations. Instead, use the same environment check for UseSentryTracing as you do for UseSentry.

0reactions
mattjohnsonpintcommented, Jul 7, 2022

No worries. Glad you have it working now! 👍

Read more comments on GitHub >

github_iconTop Results From Across the Web

Dependency Injection error: Unable to resolve service for ...
I created an .NET Core MVC application and use Dependency Injection and Repository Pattern to inject a repository to my controller. However, I ......
Read more >
Unable to resolve service for type 'Microsoft.AspNetCore. ...
I have added reference of Service inside Console application and calling the API. But here I'm getting issue that in my ExcelRender service...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found