简体   繁体   English

如何在Dot Net Core中为第三方静态类使用DI?

[英]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.

相关问题 如何在Asp.Net Core DI上注入具有不同生命周期的同一个类? - How can I inject same class with different Life Cycles on Asp.Net Core DI? 如何在通用Windows类库中使用最新的dot net core? - How to use latest dot net core in Universal Windows Class Library? 我可以在 dot net core 控制台应用程序中使用 BackgroundService - Can I use BackgroundService in dot net core console application C#.Net Core 2 DI,如何使用 class 注册接口,该接口也采用与构造函数相同的接口作为参数(装饰器) - C# .Net Core 2 DI, how can I register an interface with a class that also take the same interface as constructor a parameter (Decorator) 我如何在 dot net Core 中安排应用程序 dll 文件 - How can i Arrange app dll files in dot net Core 如何在.net Core 2.0单元测试项目中将DI与Startup类一起使用 - How to use DI with Startup class in .net Core 2.0 Unit Test project 如何在ASP.NET Web API项目而不是.NET Core上使用DI - How do I use DI on asp.net web api project not .net core 我应该如何使用 .net core DI 实例化单个类的多个实例? - How should I instantiate multiple instances of a single class with .net core DI? 如何告诉Json.NET忽略第三方对象中的属性? - How can I tell Json.NET to ignore properties in a 3rd-party object? 如何使用protobuf-net或其他序列化程序序列化第三方类型? - How can I serialize a 3rd party type using protobuf-net or other serializers?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM