0

I'm using Mapster for mapping and Simple Injector in my .net framework 4.8 MVC and WebApi controllers. I'd like to inject Mapster as a dependency in my services but I can't figure it out how to make it work with Simple Injector. The Mapster documentation is really vague in my opinion:

Mapster - Dependency Injection

Mapster - References

Can someone provide and example of how to use Mapster with Simple Injector? Doesn't matter if the controller is mvc or a web api.

The code I need is the configuration in Application_Start in Global.asax.cs and in the service concrete. Thanks!

0

1 Answer 1

0

I'm unfamiliar with Mapster, but after looking at the documentation link you provided, I'm assuming that integrating with Simple Injector can be done as follows:

var config = new TypeAdapterConfig();
container.RegisterInstance(config);
services.RegisterSingleton<IMapper, SimpleInjectorMapper>();

Where SimpleInjectorMapper is:

public sealed class SimpleInjectorMapper : ServiceMapper
{
    public SimpleInjectorMapper(
        Container container, TypeAdapterConfig config)
        : base(container, config)
    {
    }
}

The 'trick' here is that the Simple Injector Container class implements System.IServiceProvider, which is the base interface used by most of the DI facilities in .NET and .NET Core and is the base interface that the MS.DI abstraction relies on. Mapsters ServiceMapper expects an IServiceProvider in its constructor, which is now provided using the Container.

There are a few downsides to this approach. Main downside is that in case a dependency is missing, you'll get a more generic "no service registered" exception in line with what MS.DI would throw, instead of a very information rich exception that Simple Injector would throw in case the resolve would fail when you call Container.GetInstance.

This, however, is a as far as I can go in providing an answer. If you wish to integrate more deeply with Simple Injector, you likely need a more complex SimpleInjectorMapper implementation, but others (e.g. the designers behind Mapster) need to help you with that. At least, hopefully, this answer will get you started.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.