Asp.net core 执行DI时为服务指定选项的干净方法

Asp.net core 执行DI时为服务指定选项的干净方法,asp.net-core,Asp.net Core,所以我有一个服务,比如说,它是一个ASPNET核心上的电子邮件服务 当我将我的服务添加到ASPNET DI容器时,我希望在我的IServiceCollection上应用以下模式来设置我的服务 public interface IEmailService { void SendMail(string recipient, string message); } public void ConfigureServices(IServiceCollection services) { /

所以我有一个服务,比如说,它是一个ASPNET核心上的电子邮件服务

当我将我的服务添加到ASPNET DI容器时,我希望在我的IServiceCollection上应用以下模式来设置我的服务

public interface IEmailService
{
    void SendMail(string recipient, string message);
}
public void ConfigureServices(IServiceCollection services)
{
    //configures my service
    services.AddEmailService<MyEmailService>(options => options.UseEmailServer(sender, smtpHost, smtpPort, smtpPassword));
}
公共接口IEmailService
{
void SendMail(字符串收件人、字符串消息);
}
public void配置服务(IServiceCollection服务)
{
//配置我的服务
services.AddEmailService(options=>options.useMailServer(发件人、smtpHost、smtpPort、smtpPassword));
}

如果可能的话,我想知道最好的方法是什么。我确信我需要为IServiceCollection上的.AddEmailService()方法创建一个扩展方法,但除此之外,我不确定从何处开始或查看。

下面是一个带有注释的示例应用程序,让您了解不同的操作:

公共类启动
{
public void配置服务(IServiceCollection服务)
{
//添加选项内容。这将允许您注入IOptions。
services.AddOptions();
//这将负责添加和配置电子邮件服务。
服务。AddEmailService(选项=>
{
options.Host=“some Host.com”;
选项。端口=25;
选项。发件人=”firstname@lastname.com";
options.Username=“email”;
options.Password=“sup4r-secr3t!”;
});
}
public void配置(IApplicationBuilder应用程序、ILoggerFactory loggerFactory)
{
//确保我们添加了控制台记录器。
loggerFactory.AddConsole();
应用程序使用(异步(上下文,下一步)=>
{
//从服务中检索电子邮件服务。
var emailService=context.RequestServices.GetRequiredService();
//发送电子邮件
等待emailService.SendMail(“hello@recipient.com“,“你好,世界!”);
});
}
公共静态void Main(字符串[]args)
{
WebApplication.Run(args);
}
}
公共接口IEmailService
{
任务发送邮件(字符串收件人、字符串消息);
}
公共类电子邮件选项
{
公共字符串发送方{get;set;}
公共字符串主机{get;set;}
公共int端口{get;set;}
公共字符串用户名{get;set;}
公共字符串密码{get;set;}
}
公共类MyEmailService:IEmailService
{
公共MyEmailService(IOptions选项、ILogger记录器)
{
Options=Options;//这包含我们配置的实例。
记录器=记录器;
}
私有IOptions选项{get;}
专用ILogger记录器{get;}
公共任务SendMail(字符串收件人、字符串消息)
{
//发送电子邮件
var builder=新的StringBuilder();
AppendLine($“主机:{Options.Value.Host}”);
AppendLine($“端口:{Options.Value.Port}”);
AppendLine($“用户名:{Options.Value.Username}”);
AppendLine($“密码:{Options.Value.Password}”);
建筑商。附录行(“-------------------”;
AppendLine($“From:{Options.Value.Sender}”);
AppendLine($“To:{recipient}”);
建筑商。附录行(“-------------------”;
AppendLine($“Message:{Message}”);
Logger.LogInformation(builder.ToString());
返回Task.FromResult(0);
}
}
公共静态类ServiceCollectionExtensions
{
公共静态IServiceCollection AddEmailService(此IServiceCollection服务,操作配置)
其中TEmailService:class,IEmailService
{
//配置EmailOptions,并将其作为IOOptions注册到服务集合中。
服务。配置(Configure);
//将服务本身添加到集合中。
return services.AddSingleton();
}
}
下面是在控制台中运行的应用程序:

如您所见,应用程序正在从配置的
EmailOptions
中提取一些信息,并从传入的参数中提取一些信息

编辑:以下是所需的软件包:

"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.Extensions.OptionsModel": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final"
这里有类似的问题