.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;
}
}