asp.net-core - 在执行 DI 时为服务指定选项的简洁方法

标签 asp.net-core

所以我有一个服务,例如它是 ASPNET Core 上的电子邮件服务。

当我将我的服务添加到 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));
}

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

最佳答案

这是一个带有注释的示例应用程序,可让您了解不同的事情在做什么:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add the options stuff. This will allow you to inject IOptions<T>.
        services.AddOptions();

        // This will take care of adding and configuring the email service.
        services.AddEmailService<MyEmailService>(options =>
        {
            options.Host = "some-host.com";
            options.Port = 25;
            options.Sender = "firstname@lastname.com";

            options.Username = "email";
            options.Password = "sup4r-secr3t!";
        });
    }

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        // Make sure we add the console logger.
        loggerFactory.AddConsole();

        app.Use(async (context, next) =>
        {
            // Retrieve the email service from the services.
            var emailService = context.RequestServices.GetRequiredService<IEmailService>();

            // Send the email
            await emailService.SendMail("hello@recipient.com", "Hello World!");
        });
    }

    public static void Main(string[] args)
    {
        WebApplication.Run<Startup>(args);
    }
}

public interface IEmailService
{
    Task SendMail(string recipient, string message);
}

public class EmailOptions
{
    public string Sender { get; set; }

    public string Host { get; set; }

    public int Port { get; set; }

    public string Username { get; set; }

    public string Password { get; set; }
}

public class MyEmailService : IEmailService
{
    public MyEmailService(IOptions<EmailOptions> options, ILogger<MyEmailService> logger)
    {
        Options = options; // This contains the instance we configured.
        Logger = logger;
    }

    private IOptions<EmailOptions> Options { get; }

    private ILogger<MyEmailService> Logger { get; }

    public Task SendMail(string recipient, string message)
    {
        // Send the email

        var builder = new StringBuilder();

        builder.AppendLine($"Host: {Options.Value.Host}");
        builder.AppendLine($"Port: {Options.Value.Port}");
        builder.AppendLine($"Username: {Options.Value.Username}");
        builder.AppendLine($"Password: {Options.Value.Password}");
        builder.AppendLine("---------------------");
        builder.AppendLine($"From: {Options.Value.Sender}");
        builder.AppendLine($"To: {recipient}");
        builder.AppendLine("---------------------");
        builder.AppendLine($"Message: {message}");

        Logger.LogInformation(builder.ToString());

        return Task.FromResult(0);
    }
}

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddEmailService<TEmailService>(this IServiceCollection services, Action<EmailOptions> configure)
        where TEmailService : class, IEmailService
    {
        // Configure the EmailOptions and register it in the service collection, as IOptions<EmailOptions>.
        services.Configure(configure);

        // Add the service itself to the collection.
        return services.AddSingleton<IEmailService, TEmailService>();
    }
}

这是在控制台中运行的应用程序:

Application Running

如您所见,应用程序正在从配置的 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"

关于asp.net-core - 在执行 DI 时为服务指定选项的简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35178524/

相关文章:

asp.net-core - 在 ASP.NET core 2.1 中获取请求的时间

asp.net-core - 如何在 AspNet.Core 2.1 中通过依赖注入(inject)添加 UserManager?

entity-framework - 在 ASP.NET Core Windows 服务项目中解析 EFv6.3 中的连接字符串

c# - ASP.Net 核心 MVC FromQuery DateTime in utc

c# - 如何在 ASP.NET 样板中设置社交登录?

asp.net-mvc - Crystal 报表与 Blazor

c# - 如何从 AppSettings 读取配置值并将配置注入(inject)接口(interface)实例

.net - 以 JSON 消息的形式返回异常

asp.net-core - ASP.NET Core 2 迁移错误。找不到与命令 "dotnet-ef"匹配的可执行文件

c# - .NET Core 2 中的 ReadAsMultipartAsync 等价物