.net core注入服务

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_23050697/article/details/78387572

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

public void ConfigureServices(IServiceCollection services)
{
    //注入服务
    services.AddTransient();
    //或者
    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;
    }
}

展开阅读全文

没有更多推荐了,返回首页