MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.29k stars 327 forks source link

MapContext.Current is null #587

Closed arit1988 closed 1 year ago

arit1988 commented 1 year ago

.net 6.0 when use MapContext.Current.GetService to get service,an exception happened

An unhandled exception has occurred while executing the request. System.InvalidOperationException: Mapping must be called using ServiceAdapter at Mapster.TypeAdapterExtensions.GetService[TService](MapContext context) at mapster_codegen.ApiMapper.MapToExisting(Source p1, Dest p2) in O:\Projects\test\mapster-codegen\Mappers\ApiMapper.g.cs:line 12 at mapster_codegen.Controllers.WeatherForecastController.Get() in O:\Projects\test\mapster-codegen\Controllers\WeatherForecastController.cs:line 28 at lambda_method4(Closure, Object, Object[]) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)

andrerav commented 1 year ago

Hi arit1988, Can you tell me more about what kind of project/program this code is executed in? I am aware that in async code, you may run into issues in some circumstances. This is because Mapster currently uses AsyncLocal to store the mapping context, but fails to propagate the thread context in some instances, which leads to the mapping context being null. I added a preprocessing flag called MAPSTER_FORCE_LEGACY_MAPCONTEXT that will use ThreadStatic instead of AsyncLocal, which may work better in some of these cases. It's available if you use the latest pre-release package.