LuckyPennySoftware/MediatR · critical · InvalidOperationException

Could not create wrapper for type {notificationType}

Error message

Could not create wrapper for type {notificationType}

What it means

PublishNotification closes NotificationHandlerWrapperImpl<TNotification> and activates it. The throw fires only if Activator.CreateInstance returns null for this internal wrapper type — again an internal-invariant violation rather than a user-facing condition.

Source

Thrown at src/MediatR/Mediator.cs:155

            _ => throw new ArgumentException($"{nameof(notification)} does not implement ${nameof(INotification)}")
        };

    /// <summary>
    /// Override in a derived class to control how the tasks are awaited. By default the implementation calls the <see cref="INotificationPublisher"/>.
    /// </summary>
    /// <param name="handlerExecutors">Enumerable of tasks representing invoking each notification handler</param>
    /// <param name="notification">The notification being published</param>
    /// <param name="cancellationToken">The cancellation token</param>
    /// <returns>A task representing invoking all handlers</returns>
    protected virtual Task PublishCore(IEnumerable<NotificationHandlerExecutor> handlerExecutors, INotification notification, CancellationToken cancellationToken) 
        => _publisher.Publish(handlerExecutors, notification, cancellationToken);

    private Task PublishNotification(INotification notification, CancellationToken cancellationToken = default)
    {
        var handler = _notificationHandlers.GetOrAdd(notification.GetType(), static notificationType =>
        {
            var wrapperType = typeof(NotificationHandlerWrapperImpl<>).MakeGenericType(notificationType);
            var wrapper = Activator.CreateInstance(wrapperType) ?? throw new InvalidOperationException($"Could not create wrapper for type {notificationType}");
            return (NotificationHandlerWrapper)wrapper;
        });

        return handler.Handle(notification, _serviceProvider, PublishCore, cancellationToken);
    }


    public IAsyncEnumerable<TResponse> CreateStream<TResponse>(IStreamRequest<TResponse> request, CancellationToken cancellationToken = default)
    {
        if (request == null)
        {
            throw new ArgumentNullException(nameof(request));
        }

        var streamHandler = (StreamRequestHandlerWrapper<TResponse>)_streamRequestHandlers.GetOrAdd(request.GetType(), static requestType =>
        {
            var wrapperType = typeof(StreamRequestHandlerWrapperImpl<,>).MakeGenericType(requestType, typeof(TResponse));
            var wrapper = Activator.CreateInstance(wrapperType) ?? throw new InvalidOperationException($"Could not create wrapper for type {requestType}");

View on GitHub (pinned to 916ef1b3d6)

Solutions

  1. Use an unmodified released MediatR assembly.
  2. Preserve MediatR wrapper types under trimming/AOT or avoid reflection-based dispatch.
  3. Run under full trust.
Defensive patterns

Strategy: try-catch

Try / catch

try { await mediator.Publish(notification, ct); }
catch (InvalidOperationException ex) when (ex.Message.Contains("Could not create wrapper"))
{ /* internal-invariant: verify MediatR assembly, AOT/trim, trust level */ throw; }

Prevention

When it happens

Trigger: A valid INotification is published and the cached wrapper factory's Activator.CreateInstance returns null for the closed NotificationHandlerWrapperImpl type.

Common situations: Trimming/AOT removing the wrapper type, partial-trust reflection restrictions, or a corrupted/modified MediatR assembly. Not reachable in a normal full-trust host.

Related errors


AI-assisted analysis of LuckyPennySoftware/MediatR@916ef1b3d6 (2026-08-13). Data as JSON: /api/errors/b9b81bfef43a2787. Report an issue: GitHub.