欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.net core注入服务

程序员文章站 2024-01-04 11:02:58
...

1.在Startup的ConfigureServices里面,通过IServiceCollection进行注入

public void ConfigureServices(IServiceCollection services)
{
    //注入服务
    services.AddTransient<IEmailSender, EmailSender>();
    //或者
    services.Add(new ServiceDescriptor(typeof(IEmailSender), typeof(IEmailSender), ServiceLifetime.Singleton));
}

2.定义接口并实现

public interface IEmailSender
{
    Task SendEmailAsync(string email, string subject, string message);
}

public class EmailSender : IEmailSender
{
    public Task SendEmailAsync(string email, string subject, string message)
    {
        //......
    }
}

3.使用

public class AccountController : Controller
{
    private readonly IEmailSender _emailSender;
    public AccountController(IEmailSender emailSender)
    {
        _emailSender = emailSender;
    }
}

上一篇:

下一篇: