Skip to content

Compilation failures! exception when injecting services into Wolverine HTTP endpoint #463

Closed

Description

@lofbacke

I have an endpoint implemented as follows:

public sealed record RequestPasswordResetRequest(string EmailAddress);

public static class RequestPasswordResetEndpoint
{
    [WolverinePut($"{Routes.Users}/request-password-reset")]
    public static async Task RequestPasswordReset(
        RequestPasswordResetRequest request,
        IMessageBus bus,
        IUserService userService)
    {
        var userId = await userService.GetUserIdByEmailAddress(request.EmailAddress);
        if (!userId.HasValue)
            return;

        var cmd = new RequestPasswordReset(userId.Value, request.EmailAddress);
        await bus.InvokeAsync(cmd);
    }
}

public sealed record RequestPasswordReset(Guid UserId, string EmailAddress);

public static class RequestPasswordResetAggregateHandler
{
    public static IEnumerable<object> Handle(RequestPasswordReset _, User user)
    {
        user.RequestPasswordReset();
        return user.Changes;
    }
}

IUserService is registered as a scoped service. The concrete implementation takes a dependency on Marten's IQuerySession and nothing else.

When I hit the endpoint at runtime, the following error message is returned:

System.InvalidOperationException: Compilation failures!

CS1503: Argument 1: cannot convert from 'Wolverine.IMessageContext' to 'Wolverine.Runtime.MessageContext'

Code:

// <auto-generated/>
#pragma warning disable
using Microsoft.AspNetCore.Routing;
using System;
using System.Linq;
using Wolverine.Http;
using Wolverine.Marten.Publishing;
using Wolverine.Runtime;

namespace Internal.Generated.WolverineHandlers
{
    // START: PUTapi_users_request_password_reset
    public class PUTapi_users_request_password_reset : Wolverine.Http.HttpHandler
    {
        private readonly Wolverine.Http.WolverineHttpOptions _options;
        private readonly Wolverine.Runtime.IWolverineRuntime _wolverineRuntime;
        private readonly Wolverine.Marten.Publishing.OutboxedSessionFactory _outboxedSessionFactory;

        public PUTapi_users_request_password_reset(Wolverine.Http.WolverineHttpOptions options, Wolverine.Runtime.IWolverineRuntime wolverineRuntime, Wolverine.Marten.Publishing.OutboxedSessionFactory outboxedSessionFactory) : base(options)
        {
            _options = options;
            _wolverineRuntime = wolverineRuntime;
            _outboxedSessionFactory = outboxedSessionFactory;
        }



        public override async System.Threading.Tasks.Task Handle(Microsoft.AspNetCore.Http.HttpContext httpContext)
        {
            var messageContext = new Wolverine.Runtime.MessageContext(_wolverineRuntime);
            await using var querySession = _outboxedSessionFactory.QuerySession(((Wolverine.IMessageContext)messageContext));
            var userService = new Namespace.Here.Users.Services.UserService(querySession);
            try
            {
                Wolverine.Http.Runtime.RequestIdMiddleware.Apply(httpContext, ((Wolverine.IMessageContext)messageContext));
                var (request, jsonContinue) = await ReadJsonAsync<Namespace.Here.Users.Features.RequestPasswordResetRequest>(httpContext);
                if (jsonContinue == Wolverine.HandlerContinuation.Stop) return;
                await Namespace.Here.Users.Features.RequestPasswordResetEndpoint.RequestPasswordReset(request, ((Wolverine.IMessageBus)messageContext), userService).ConfigureAwait(false);
                // Wolverine automatically sets the status code to 204 for empty responses
                httpContext.Response.StatusCode = 204;
            }


            catch(System.Exception ex) when (Namespace.Here.HttpExceptionPolicy.CanHandleException(ex))
            {
                await Namespace.Here.HttpExceptionPolicy.HandleException(ex, httpContext);
                return;
            }


        }

    }

    // END: PUTapi_users_request_password_reset
    
    
}


   at JasperFx.RuntimeCompiler.AssemblyGenerator.Generate(String code)
   at JasperFx.RuntimeCompiler.AssemblyGenerator.Compile(GeneratedAssembly generatedAssembly, IServiceVariableSource services)
   at JasperFx.RuntimeCompiler.CodeFileExtensions.InitializeSynchronously(ICodeFile file, GenerationRules rules, ICodeFileCollection parent, IServiceProvider services)
   at Wolverine.Http.HttpChain.<>c__DisplayClass66_0.<BuildEndpoint>b__0()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at Wolverine.Http.HttpChain.<>c__DisplayClass66_0.<BuildEndpoint>b__1(HttpContext c)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
--- End of stack trace from previous location ---
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

Activity

  1. lofbacke commented on Jul 9, 2023

    @lofbacke
    Author

    @jeremydmiller FYI, I am now receiving a similar exception when I try converting to aggregate handlers and HTTP endpoints in a single method and utilize the discard (_) naming convention for the command object. In this case, I only need the command object for the UserId, not the business logic itself.

    public sealed record EnableUser(Guid UserId);
    
    public static class EnableUserEndpoint
    {
        [AggregateHandler]
        [Authorize(Policy = Policies.Admin)]
        [WolverinePut($"{Routes.Users}/enable")]
        public static IEnumerable<object> EnableUser(EnableUser _, User user)
        {
            user.Enable();
    
            return user.Changes;
        }
    }

    It results in the following exception. If I change the name back to cmd, it works.

    System.InvalidOperationException: Compilation failures!
    
    CS0103: The name '_' does not exist in the current context
    CS0103: The name '_' does not exist in the current context
    
    Code:
    
    // <auto-generated/>
    #pragma warning disable
    using Microsoft.AspNetCore.Routing;
    using System;
    using System.Linq;
    using Wolverine.Http;
    using Wolverine.Marten.Publishing;
    using Wolverine.Runtime;
    
    namespace Internal.Generated.WolverineHandlers
    {
        // START: PUTapi_users_enable
        public class PUTapi_users_enable : Wolverine.Http.HttpHandler
        {
            private readonly Wolverine.Http.WolverineHttpOptions _options;
            private readonly Wolverine.Marten.Publishing.OutboxedSessionFactory _outboxedSessionFactory;
            private readonly Wolverine.Runtime.IWolverineRuntime _wolverineRuntime;
    
            public PUTapi_users_enable(Wolverine.Http.WolverineHttpOptions options, Wolverine.Marten.Publishing.OutboxedSessionFactory outboxedSessionFactory, Wolverine.Runtime.IWolverineRuntime wolverineRuntime) : base(options)
            {
                _options = options;
                _outboxedSessionFactory = outboxedSessionFactory;
                _wolverineRuntime = wolverineRuntime;
            }
    
    
    
            public override async System.Threading.Tasks.Task Handle(Microsoft.AspNetCore.Http.HttpContext httpContext)
            {
                var messageContext = new Wolverine.Runtime.MessageContext(_wolverineRuntime);
                try
                {
                    var (_, jsonContinue) = await ReadJsonAsync<GulfAndOhio.Dispatching.Application.Users.Features.EnableUser>(httpContext);
                    if (jsonContinue == Wolverine.HandlerContinuation.Stop) return;
                    await using var documentSession = _outboxedSessionFactory.OpenSession(messageContext);
                    var eventStore = documentSession.Events;
                    
                    // Loading Marten aggregate
                    var eventStream = await eventStore.FetchForWriting<GulfAndOhio.Dispatching.Domain.Users.User>(_.UserId, httpContext.RequestAborted).ConfigureAwait(false);
    
                    var objectIEnumerable = GulfAndOhio.Dispatching.Application.Users.Features.EnableUserEndpoint.EnableUser(_, eventStream.Aggregate);
                    if (objectIEnumerable != null)
                    {
                        
                        // Capturing any possible events returned from the command handlers
                        eventStream.AppendMany(objectIEnumerable);
    
                    }
    
                    await documentSession.SaveChangesAsync(httpContext.RequestAborted).ConfigureAwait(false);
                    // Wolverine automatically sets the status code to 204 for empty responses
                    httpContext.Response.StatusCode = 204;
                }
    
    
                catch(System.Exception ex) when (GulfAndOhio.Dispatching.Application.HttpExceptionPolicy.CanHandleException(ex))
                {
                    await GulfAndOhio.Dispatching.Application.HttpExceptionPolicy.HandleException(ex, httpContext);
                    return;
                }
    
    
            }
    
        }
    
        // END: PUTapi_users_enable
        
        
    }
    
    
       at JasperFx.RuntimeCompiler.AssemblyGenerator.Generate(String code)
       at JasperFx.RuntimeCompiler.AssemblyGenerator.Compile(GeneratedAssembly generatedAssembly, IServiceVariableSource services)
       at JasperFx.RuntimeCompiler.CodeFileExtensions.InitializeSynchronously(ICodeFile file, GenerationRules rules, ICodeFileCollection parent, IServiceProvider services)
       at Wolverine.Http.HttpChain.<>c__DisplayClass66_0.<BuildEndpoint>b__0()
       at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
       at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
       at System.Lazy`1.CreateValue()
       at Wolverine.Http.HttpChain.<>c__DisplayClass66_0.<BuildEndpoint>b__1(HttpContext c)
       at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
    --- End of stack trace from previous location ---
       at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
       at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
       at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
       at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
       at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
    

    The offending code is located on lines 39 and 41 per the screenshot below.
    image

  2. lofbacke commented on Jul 9, 2023

    @lofbacke
    Author

    At the risk of becoming a squeaky wheel, I've now encountered a third scenario that produces this exception. Details below.

    Endpoint:

    public sealed record RefreshTokens(string RefreshToken);
    
    public static class RefreshTokensEndpoint
    {
        [WolverinePost($"{Routes.Auth}/refresh-tokens")]
        public static async Task<AuthResult> RefreshTokens(
            RefreshTokens cmd,
            HttpContext httpContext,
            TokenFactory tokenFactory,
            IDocumentSession session)
        {
            var refreshToken = await session.LoadAsync<RefreshToken>(cmd.RefreshToken)
                ?? throw new AuthorizationException();
    
            var ipAddress = httpContext.GetIpAddress();
    
            var userDetails = await session.LoadAsync<UserDetails>(refreshToken.UserId);
            if (refreshToken.CreatedByIp != ipAddress || refreshToken.ExpiresOn <= DateTime.UtcNow ||
                userDetails is null || userDetails.IsDisabled)
            {
                session.Delete(refreshToken);
                await session.SaveChangesAsync();
                throw new AuthorizationException();
            }
    
            var newJwtToken = await tokenFactory.GenerateJwtToken(userDetails.Id, userDetails.EmailAddress, userDetails.Role);
            var newRefreshToken = tokenFactory.GenerateRefreshToken(userDetails.Id, ipAddress);
    
            userDetails.LastActive = DateTime.UtcNow;
    
            session.DeleteRefreshTokens(userDetails.Id);
            session.Store(newRefreshToken);
    
            return new AuthResult(newJwtToken, newRefreshToken.Token);
        }
    }

    TokenFactory takes a dependency on IOptions<JwtIssuerOptions> and nothing else. The factory and the options are both registered with the IoC container.

    Exception message:

    System.InvalidOperationException: Compilation failures!
    
    CS0103: The name 'options' does not exist in the current context
    
    Code:
    
    // <auto-generated/>
    #pragma warning disable
    using Marten;
    using Microsoft.AspNetCore.Routing;
    using Microsoft.Extensions.Options;
    using System;
    using System.Linq;
    using Wolverine.Http;
    
    namespace Internal.Generated.WolverineHandlers
    {
        // START: POSTapi_auth_refresh_tokens
        public class POSTapi_auth_refresh_tokens : Wolverine.Http.HttpHandler
        {
            private readonly Wolverine.Http.WolverineHttpOptions _options1;
            private readonly Microsoft.Extensions.Options.IOptions<Namespace.Here.Auth.Jwt.JwtIssuerOptions> _options2;
            private readonly Marten.ISessionFactory _sessionFactory925279307;
    
            public POSTapi_auth_refresh_tokens(Wolverine.Http.WolverineHttpOptions __options1, Microsoft.Extensions.Options.IOptions<Namespace.Here.Auth.Jwt.JwtIssuerOptions> __options2, [Lamar.Named("lightweightSessionFactory")] Marten.ISessionFactory sessionFactory925279307) : base(options)
            {
                _options1 = __options1;
                _options2 = __options2;
                _sessionFactory925279307 = sessionFactory925279307;
            }
    
    
    
            public override async System.Threading.Tasks.Task Handle(Microsoft.AspNetCore.Http.HttpContext httpContext)
            {
                await using var documentSession = _sessionFactory925279307.OpenSession();
                var tokenFactory = new Namespace.Here.Auth.Jwt.TokenFactory(_options2);
                try
                {
                    var (cmd, jsonContinue) = await ReadJsonAsync<Namespace.Here.Auth.Features.RefreshTokens>(httpContext);
                    if (jsonContinue == Wolverine.HandlerContinuation.Stop) return;
                    var authResult = await Namespace.Here.Auth.Features.RefreshTokensEndpoint.RefreshTokens(cmd, httpContext, tokenFactory, documentSession).ConfigureAwait(false);
                    
                    // Commit any outstanding Marten changes
                    await documentSession.SaveChangesAsync(httpContext.RequestAborted).ConfigureAwait(false);
    
                    await WriteJsonAsync(httpContext, authResult);
                }
    
    
                catch(System.Exception ex) when (Namespace.Here.HttpExceptionPolicy.CanHandleException(ex))
                {
                    await Namespace.Here.HttpExceptionPolicy.HandleException(ex, httpContext);
                    return;
                }
    
    
            }
    
        }
    
        // END: POSTapi_auth_refresh_tokens
        
        
    }
    
    
       at JasperFx.RuntimeCompiler.AssemblyGenerator.Generate(String code)
       at JasperFx.RuntimeCompiler.AssemblyGenerator.Compile(GeneratedAssembly generatedAssembly, IServiceVariableSource services)
       at JasperFx.RuntimeCompiler.CodeFileExtensions.InitializeSynchronously(ICodeFile file, GenerationRules rules, ICodeFileCollection parent, IServiceProvider services)
       at Wolverine.Http.HttpChain.<>c__DisplayClass66_0.<BuildEndpoint>b__0()
       at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
       at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
       at System.Lazy`1.CreateValue()
       at Wolverine.Http.HttpChain.<>c__DisplayClass66_0.<BuildEndpoint>b__1(HttpContext c)
       at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
    --- End of stack trace from previous location ---
       at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
       at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
       at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
       at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
       at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
    

    And the compilation error in the generated code happens in the constructor method where it passes the options argument to the base constructor. It doesn't differentiate between the WolverineHttpOptions argument and the JwtIssuerOptions argument.

  3. added this to the 1.1.4 milestone on Jul 10, 2023
  4. jeremydmiller commented on Jul 10, 2023

    @jeremydmiller
    Member

    @lofbacke Got the first one fixed locally. Starting the others now.

  5. jeremydmiller commented on Jul 10, 2023

    @jeremydmiller
    Member

    Pfft, found some other issues while working through this.

  6. lofbacke commented on Jul 10, 2023

    @lofbacke
    Author

    Thanks for the quick turnaround, @jeremydmiller!

  7. added a commit that references this issue on Feb 5, 2024
    ab4e9ad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions