7

I'd like to know if there is a way to globally configure Mapster while using Dependency Injection?

The configuration options appear to be for the static usage and also for a singleton pattern only.

Mapster Configuration

Mapster Dependency Injection

I have created an extension method.

// Extension method
public static IServiceCollection AddMapster(this IServiceCollection services, Action<TypeAdapterConfig> options = null)
{
    var config = new TypeAdapterConfig();
    config.Scan(Assembly.GetAssembly(typeof(Startup)));

    options?.Invoke(config);

    services.AddSingleton(config);
    services.AddScoped<IMapper, ServiceMapper>();

    return services;
}

// Called in Startup.ConfigureServices(IServiceCollection services)
services.AddMapster(options =>
{
    options.Default.IgnoreNonMapped(true); // Does not work.
    TypeAdapterConfig.GlobalSettings.Default.IgnoreNonMapped(true); // Does not work.
});

I imagine these don't work because the ServiceMapper is creating its own instance without using anything I've configured.

Fosol
  • 137
  • 1
  • 6
  • 2
    Obviously the author doesn't really realize the importance of documentation, in terms of promoting a library. – Nico Mar 21 '22 at 10:49

2 Answers2

10

I implemented Mapster in a Blazor Server application, and I struggled to find documentation on how to scan the assembly for mapping registrations.

I have a class in my application that implements the IRegister interface and defines the mappings

public class MappingRegistration : IRegister
{
    void IRegister.Register(TypeAdapterConfig config)
    {
        config.NewConfig<ModelA, ModelB>();
    }
}

In the ConfigureServices of the Startup.cs I have this then

var typeAdapterConfig = TypeAdapterConfig.GlobalSettings;
// scans the assembly and gets the IRegister, adding the registration to the TypeAdapterConfig
typeAdapterConfig.Scan(Assembly.GetExecutingAssembly());
// register the mapper as Singleton service for my application
var mapperConfig = new Mapper(typeAdapterConfig);
services.AddSingleton<IMapper>(mapperConfig);

I hope this can save someone's time. If anybody is aware of better ways, please let me know.

DaemonFire
  • 573
  • 6
  • 13
ab_732
  • 3,639
  • 6
  • 45
  • 61
4

You can change from

var config = new TypeAdapterConfig();

to

var config = TypeAdapterConfig.GlobalSettings;
  • 2
    You definitely should add it to your documentation on github. I have spent almost an hour looking for this. I even asked a question in the documentation directly: https://github.com/MapsterMapper/Mapster/wiki/Dependency-Injection :) – manymanymore Jun 04 '20 at 20:08