Skip to content

Dependency Injection (DI) Support #1244

Closed Answered by latonz
fruitbatinshades asked this question in Q&A
Discussion options

You must be logged in to vote

You simply inject _diContainer into your mapper.

Example:

// registration
serviceCollection.AddSingleton<BOMapper>();
serviceCollection.AddSingleton<BO>();
serviceCollection.AddSingleton<IAmADependent>();

// mapper
[Mapper]
public partial class BOMapper(IServiceProvider sp)
{
    [ObjectFactory]
    private T Create<T>()
        where T : class
        => sp.GetRequiredService<T>();
    
    public partial BO Map(DTO dto);
}

// invocation / mapper call
var serviceProvider = serviceCollection.BuildServiceProvider();
var mapper = serviceProvider.GetRequiredService<BOMapper>();
var bo = mapper.Map(new DTO());

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@latonz
Comment options

Answer selected by fruitbatinshades
@fruitbatinshades
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants