1

Please help me sort it out.. ;)

How to inject a dependency in a static class?

I want to inject Mapper into a static class. I read the documentation and google about LightInject and did not find how to implement it .. Or is there a better solution for my task, not only through DI?

public static class MapExtension
{
    public static IMapper Mapper { get; set; }

    public static TModel Map<TModel, TData>(TData data)
        where TModel : IModel
        where TData : IData
    {

        TModel model = Mapper.Map<TModel>(data);

        return model;
    }
}

I use:

  • ASP.NET CORE MVC 3
  • LightInject 6.3.4 (latest version)
  • AutoMapper 10.0.0
Nikita
  • 64
  • 10
  • 3
    Dependency injection doesn't compose with static classes. As for whether there is a better solution for your task, you've provided no context from which anyone could determine that. – Aluan Haddad Jul 15 '20 at 19:34
  • 1
    As of AutoMapper 9.0 [static API was removed](https://docs.automapper.org/en/stable/9.0-Upgrade-Guide.html#the-static-api-was-removed) to improve thread-safety. AutoMapper by default is added to the service collection as transient service, meaning a new instance is created each time it is requested from the service container. What you are trying do to here is preserve one mapper instance and basically that's the feature that was removed in 9.0 version. – Prolog Jul 15 '20 at 19:53
  • As of solutions - you could pass the mapper instance resolved via DI in an other non-static class (like controller) to the static method via parameter. If that's not good for you, then you could also [assign the mapper instance during application startup](https://stackoverflow.com/a/56333343/8065832). Also, the code you showed looks very similar to an [extension method](https://learn.microsoft.com/en-gb/dotnet/csharp/programming-guide/classes-and-structs/extension-methods). Maybe you could convert the whole class to just a bunch of extension methods for mapper instance? – Prolog Jul 15 '20 at 19:54
  • 1
    Related: https://stackoverflow.com/questions/55213803/use-dependency-injection-in-static-class – Steven Jul 16 '20 at 08:13

0 Answers0