Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register Instance in ASPNET Core DI

Tags:

asp.net-core

I am converting some code from Unity to use ASPNET Core's built in DI, I came across the following scenario that I need to register (an instance of). How can I go about doing it?

    var mapperConfig = new MapperConfiguration(cfg =>
    {
        cfg.AddProfile<AutoMapperBootstrapper.ServicesProfile>();
        cfg.AddProfile<AutoMapperBootstrapper.WebApiProfile>();
        cfg.AddProfile<AutoMapperBootstrapper.WebProfile>();
    });

    // register mapper config
    var mapper = mapperConfig.CreateMapper();

In Unity I did:

unityContainer.RegisterInstance(mapper);

But I am not sure how to do it in core.

like image 728
TheWebGuy Avatar asked Oct 24 '25 09:10

TheWebGuy


1 Answers

You can use the factory pattern of IServiceCollection.

services.AddSingleton(serviceProvider => {
    var mapperConfig = new MapperConfiguration(cfg =>
    {
        cfg.AddProfile<AutoMapperBootstrapper.ServicesProfile>();
        cfg.AddProfile<AutoMapperBootstrapper.WebApiProfile>();
        cfg.AddProfile<AutoMapperBootstrapper.WebProfile>();
    });
    return mapperConfig.CreateMapper();
});

Or just

services.AddSingleton(mapper);

like image 84
Kalten Avatar answered Oct 28 '25 06:10

Kalten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!