0

Someone in our company wrote (by mistake, a long time ago) this static class, being served from Nuget : (I can't edit it)

public static class MailService
 {

    public static void SendEmail(string recipients, string subject, string msg  )
    {
        SendEmail(recipients, subject,  msg);
    }
...
}

I already know it's bad. But let's continue.
I want to use this class via DI in my asp.net core project.
Problem is that I can't use this (because static can't be new'ed):

  services.AddSingleton<MailService>();

enter image description here

Question:

Is there still a way to make MailService (or any wrapper for it ) Injectable?

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 1
    I think this is somehow related: https://stackoverflow.com/questions/6523463/how-to-use-dependency-injection-with-static-methods ? – Paul Karam May 23 '19 at 13:20
  • 1
    Can't you wrap it in a custom class/interface (such as `MailSender`/`IMailSender`)? Call `MailService` in `MailSender` and inject `IMailSender` whenever you'll need `MailService`. – Caramiriel May 23 '19 at 13:20

1 Answers1

6

It's as simple as this:

public interface IMailService {
    void SendEmail(string recipients, string subject, string msg);
}

public class MailServiceWrapper : IMailService {
    public void SendEmail(string recipients, string subject, string msg) {
        MailService.SendEmail(recipients, subject, msg);
    }
}

And in the Startup class:

services.AddSingleton<IMailService, MailServiceWrapper>();
stuartd
  • 70,509
  • 14
  • 132
  • 163