-
Notifications
You must be signed in to change notification settings - Fork 79
FYI, how to use AutoMapper in custom ResultFilterAttribute #69
Comments
Using v4.0.1, add this in ConfigureServices, works Using v5.0.1, add this in ConfigureServices, get error "Mapper not initialized" |
Thanks for the link. Could you please give me an idea how to use _mapper.Map in a custom ResultFilterAttribute? |
I would change the question to how do you do DI in general in a custom ResultFilterAttribute. I don't have an answer to that, but surely it's possible somehow. |
With any filter, they don't want you to do constructor injection. Filters typically have a singleton lifecycle. Instead, core ASP.NET extensions pass in a using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Books.Api.Filters
{
public class BookResultFilterAttribute : ResultFilterAttribute
{
public override async Task OnResultExecutionAsync(ResultExecutingContext context,
ResultExecutionDelegate next)
{
var resultFromAction = context.Result as ObjectResult;
if (resultFromAction?.Value == null
|| resultFromAction.StatusCode < 200
|| resultFromAction.StatusCode >= 300)
{
await next();
return;
}
var mapper = context.HttpContext.RequestServices.GetService<IMapper>();
resultFromAction.Value = mapper.Map<Models.Book>(resultFromAction.Value);
await next();
}
}
} |
Awesome, thanks Jimmy, that's what I want! Just a small change on your code and it works!
|
FYI that |
You're right! 💯 |
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
Please check comments in
https://app.pluralsight.com/library/courses/building-async-api-aspdotnet-core/discussion
this function broken in v5.0.1 and works in v4.0.1
The text was updated successfully, but these errors were encountered: