1

I am working on existing code and need to rewrite or get dependency injection to work inside a static class. First, I don't want to write all static class in this project and pass the interface in the constructor. Is there a work around?

Here is what I have

public static class MyUserClass
    {
        private readonly IMyDBHelper  myDBHelper;

        public static string Get()
        {
         
             ....
            
        }
    }

When I build, I get the error

cannot declare instance members in a static class.

Thanks

Sai Gummaluri
  • 1,340
  • 9
  • 16
c0micrage
  • 1,118
  • 2
  • 21
  • 56
  • 2
    Static classes are at the opposite end of the SOLID principles. You are not going to be able to easily get DI inside a static class (other than by receiving from parameters) and you shouldn't either. – Camilo Terevinto Aug 24 '20 at 17:59
  • Related: https://stackoverflow.com/questions/52325438/how-to-inject-dependency-to-static-class – Steven Aug 24 '20 at 18:08
  • Related: https://stackoverflow.com/questions/16282223/implementing-dependency-injection-static-methods – Steven Aug 24 '20 at 18:08

0 Answers0