Search code examples
c#dependency-injectionmapster

Mapster Global Configuration with Dependency Injection


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.


Solution

  • You can change from

    var config = new TypeAdapterConfig();
    

    to

    var config = TypeAdapterConfig.GlobalSettings;