[英]How can I use DI for 3'rd party static class in Dot Net Core?
Someone in our company wrote ( by mistake, a long time ago ) this static class, being served from Nuget : (I can't edit it) 我们公司中的某个人( 很久以前就错误地 )写了这个静态类,由Nuget提供:(我无法编辑)
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. 我想在asp.net核心项目中通过DI使用此类。
Problem is that I can't use this (because static
can't be new'ed): 问题是我不能使用它(因为static
不能被更新):
services.AddSingleton<MailService>();
Question: 题:
Is there still a way to make MailService
(or any wrapper for it ) Injectable? 还有没有办法使MailService
(或其任何包装器)可注入?
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>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.