vNext控制台应用程序中的OptionsModel依赖注入

时间:2016-01-16 19:58:50

标签: dependency-injection console-application asp.net-core

我有一个 vNext控制台应用程序,其中一个类采用OptionsModel<T> POCO配置设置类。

我无法解决POCO设置类并将其注入下面的RabbitMqConnection课程。

设置ServiceProvider不是问题,而是设置类的解析。

注意,这是 vNext控制台应用程序(不是mvc6应用程序)。

我的第二个问题是,我理解构造函数参数应该保持最小,但是最好不要将两个字符串作为构造函数参数而不是IOptions类传递,因为前一个方法更能描述什么是RabbitMqConnection课要求?如果是这样,如何最好地从定义映射的类中注入(在下面的示例中为Program.cs文件)

public class RabbitMqConnection
{
    public string HostName { get; set; }
    public string UserName { get; set; }

    public RabbitMqConnection(IOptions<MessagingSettings> settings)
    {
        HostName = settings.Value.HostName;
        UserName = settings.Value.UserName;
    }
}

public class MessagingSettings
{
    public string HostName { get; set; }
    public string UserName { get; set; }
}

appsettings.json

{
    "MessagingSettings":{
        "HostName":"localhost",
        "Username":"guest"
    }
}

public void ConfigureServices(IServiceCollection services)
{
    // tried registration a number of ways as below
    services.Configure<MessagingSettings>(Configuration.GetSection("MessagingSettings"));
    services.Configure<MessagingSettings>(Configuration);

    // attempt 1 - get runtime error saying cant resolve IOptions<MessageSettings>
    services.TryAdd(ServiceDescriptor.Singleton<RabbitMqConnection, RabbitMqConnection>());

    // attempt 2 - same as above, when i breakpoint on messagingSettings, all the values in the object are null
    services.TryAdd(ServiceDescriptor.Singleton<RabbitMqConnection>(factory =>
    {
        // instead of injecting the MessageSettings, pass through the string values (constructor omitted for clarity)
        var messagingSettings = Configuration.Get<MessagingSettings>();
        return new RabbitMqConnection(messagingSettings.HostName, messagingSettings.UserName);
    }));
}

var conn = ServiceProvider.GetRequiredService<RabbitMqConnection>();

1 个答案:

答案 0 :(得分:1)

您需要致电services.AddOptions()