Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question about registering a behavior #1075

Open
bancroftway opened this issue Sep 30, 2024 Discussed in #1074 · 8 comments
Open

Question about registering a behavior #1075

bancroftway opened this issue Sep 30, 2024 Discussed in #1074 · 8 comments
Labels

Comments

@bancroftway
Copy link

bancroftway commented Sep 30, 2024

Discussed in #1074

Originally posted by bancroftway September 26, 2024
I have a question regarding correct way to register my behavior whose complete code is below.

I have tried this way, but the behavior does not get called:

 builder.Services.AddMediatR(cfg => {
     cfg.RegisterServicesFromAssemblies(typeof(Program).Assembly);
     cfg.AddBehavior<IPipelineBehavior<IAppRequest<BaseResponse>,BaseResponse>, UnhandledExceptionBehavior<IAppRequest<BaseResponse>, BaseResponse>>();
 });
public class UnhandledExceptionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IAppRequest<TResponse>
    where TResponse : BaseResponse
{
    private readonly ILogger<UnhandledExceptionBehavior<TRequest, TResponse>> _logger;

    public UnhandledExceptionBehavior(ILogger<UnhandledExceptionBehavior<TRequest, TResponse>> logger)
    {
        _logger = logger;
    }

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        try
        {
            return await next();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Unhandled Exception for Request {Name} {@Request}", typeof(TRequest).Name, request);

            var response = Activator.CreateInstance<TResponse>();
            response.IsSuccess = false;
            response.ErrorMessage = $"An error occurred while processing your request: {ex.Message}";

            return response;
        }
    }
@balogun14
Copy link

balogun14 commented Oct 7, 2024

try separating MediatR configuration from the behavior registration. like this
builder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblies(typeof(Program).Assembly);
});

builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehavior<,>));

@duongphuhiep
Copy link

try separating MediatR configuration from the behavior registration. like this builder.Services.AddMediatR(cfg => { cfg.RegisterServicesFromAssemblies(typeof(Program).Assembly); });

builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehavior<,>));

I won't work, I had the same problem

@duongphuhiep
Copy link

In order to register Generic behaviors you have to use AddOpenBehavior instead of AddBehavior for eg: cfg.AddOpenBehavior(typeof(UnhandledExceptionBehavior<,>))

@1124541815
Copy link

泛型他没有提供注入,使用atuofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer(builder =>
{
builder.RegisterSource(new ContravariantRegistrationSource());
builder.RegisterGeneric(typeof(UnhandledExceptionBehavior<,>)).AsImplementedInterfaces();
}); 看下是否可以

@tolgacakir
Copy link

can you share your request? you should inherit from IAppRequest and your response should be BaseResponse.

@bancroftway
Copy link
Author

Here is my request and response. Please help me with the registration code for the behavior as I am unable to understand the correct code to register the behavior, as this is not an open behavior

public sealed record GetTopQuestionsQry : IRequest<GetTopQuestionsQryResult>;

public sealed record GetTopQuestionsQryResult : BaseResponse
{
    public List<QuestionDto> Questions { get; set; }
}

@tolgacakir
Copy link

There are 2 ways to solve this issue:

1 - Use IRequest instead of IAppRequest in your behavior:

public class UnhandledExceptionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : **IRequest<TResponse>**
    where TResponse : BaseResponse
{
    //...
}

2 - If you want to use IAppRequest, first you must define like this:

public interface IAppRequest<T> : IRequest<T>
{
}

and define your request like this:

public sealed record GetTopQuestionsQry : IAppRequest<GetTopQuestionsQryResult>;

Copy link

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 14 days.

@github-actions github-actions bot added the Stale label Dec 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants