ab_732
ab_732

Reputation: 3907

Mapster and Blazor

I would like to plug and use Mapster in my Blazor project. I can't find a good reference on how to register mappings and get them injected in the different layers of my application.

Does anyone know how do I achieve that?

Thank you

Upvotes: 3

Views: 518

Answers (1)

ab_732
ab_732

Reputation: 3907

It turned out to be very simple.

Mapster exposes the IMapper interface that can be used to register a configuration, similar to the following:

In Startup.cs

var config = new TypeAdapterConfig();
config.NewConfig<ModelA, ModelB>()
    .Map(d => d.PropertyB, s => s.PropertyA);

var mapperConfig = new Mapper(config);
services.AddSingleton<IMapper>(mapperConfig);

Now you just need to inject the IMapper interface in your service and use it e.g.:

public MyService(IMapper mapper)
{
this.mapper = mapper;
}
...
var modelB = modelA.Adapt<ModelB>(mapper.Config);
...

This works perfectly, any thought/improvement is welcome!

Upvotes: 2

Related Questions