Mapster icon indicating copy to clipboard operation
Mapster copied to clipboard

Add an overload to the Adapt method to allow using a local, temporary configuration.

Open roohial57 opened this issue 2 weeks ago • 4 comments

Previously, I added two overload for method Adapt that locally and temporarily modified the global configuration.

public static TDestination Adapt<TDestination>(this object? source, Action<TypeAdapterConfig> configAction)
public static TDestination Adapt<TSource, TDestination>(this object? source, Action<TypeAdapterSetter<TSource, TDestination>> configAction)

What do you think about adding the following the overload to modify an existing object? public static TDestination Adapt<TSource, TDestination>(this object? source, TDestination destination, Action<TypeAdapterSetter<TSource, TDestination>> SetterAction)

And add an overload to ProjectToType method that locally and temporarily modified the global configuration. The proposed overload: public static IQueryable<TDestination> ProjectToType<TDestination>(this IQueryable source, TypeAdapterConfig? config = null, Action<TypeAdapterSetter<TSource, TDestination>> SetterAction)

Of course, the following method already exists in the current version and uses a config instead of the global setting. public static IQueryable ProjectToType(this IQueryable source, Type destinationType, TypeAdapterConfig? config = null)

roohial57 avatar Dec 06 '25 07:12 roohial57

@DocSvartz I would be happy to see your opinion.

roohial57 avatar Dec 08 '25 09:12 roohial57

@roohial57 I don't mind. Do you plan to use this to speed up test writing?

In previous PR i forgot to mention that this approach has one drawback: you lose cached versions of all mappers where the local configuration is applied.

DocSvartz avatar Dec 08 '25 09:12 DocSvartz

@DocSvartz Not just for testing. In my opinion, in most cases, defining the mapping configuration locally in the code rather than in a global configuration makes the code clearer.

Do you think losing the cache is bad enough to abandon this approach?

roohial57 avatar Dec 08 '25 11:12 roohial57

Do you think losing the cache is bad enough to abandon this approach?

I think the more complex the model, the greater the difference will be (if the cache works as I think it does).

I haven't tested this yet, but there are notes about it in the documentation.

DocSvartz avatar Dec 08 '25 11:12 DocSvartz

@roohial57 Apparently, performance is significantly reduced.

I added benchmark You can test it yourself.

There is already a test for your first adapt option here. https://github.com/DocSvartz/Mapster/tree/Test-TempConfig/src/Benchmark.Development

DocSvartz avatar Dec 14 '25 09:12 DocSvartz