'Mapster context is null in nested mappings
How I can use MapContext.Current in nested mappings? For example:
public class Foo {
public string Name { get; set; }
}
public class Bar {
public string Name { get; set; }
}
public class Src {
public IEnumerable<Foo> Foos { get; set; }
}
public class Dst {
public IEnumerable<Bar> Bars { get; set; }
public string Name { get; set; }
}
TypeAdapterConfig<Foo, Bar>
.NewConfig()
.Map(d => d.Name, s => (string)MapContext.Current.Parameters["prefix"] + s.Name);
TypeAdapterConfig<Src, Dst>
.NewConfig()
.Map(d => d.Bars, s => s.Foos)
.Map(d => d.Name, s => (string)MapContext.Current.Parameters["prefix"]);
var src = new Src
{
Foos = new [] { "test" }
};
var dst = src
.BuildAdapter()
.AddParameter("prefix", "!")
.AdaptToType<Dst>();
When i try to map a src into dst i get Null reference exception
for MapContext.Current
on attempt to map Foos into Bars. Context works for top level mappings (Dst.Name will be set) but is not accessible on nested mappings. How can I solve that?
Solution 1:[1]
It works for me if I explicitly add the call to create the MapScopeContext
:
using var contextScope = new MapContextScope();
Anyway, the ServiceMapper
implementation should already add it as found in source code.
Additionally, it used to work for me, but in a new XUnit test project I'm getting the exception:
System.InvalidOperationException: Mapping must be called using ServiceAdapter
at Mapster.TypeAdapterExtensions.GetService[TService](MapContext context)
and debugging I found that the MapContext.Current
property is null
.
I would like to understand why I'm getting this inconsistent behavior.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | fra |