具有非DI和DI参数的构造函数

时间:2017-10-23 19:03:24

标签: c# dependency-injection asp.net-core

我正在创建一项需要一些配置参数和记录器的服务。这是我服务的构造函数:

public StorageProvider(string directory, ILogger<StorageProvider> logger)

我刚刚添加了记录器。我曾经在我的startup.cs中像这样初始化它:

services.AddSingleton<IStorageProvider>(
    new StorageProvider(Configuration["TempStorage.Path"]));

directory参数来自配置文件,记录器获取DI。如何设置IStorageProvider

2 个答案:

答案 0 :(得分:2)

您应该执行以下操作:

  • 将配置值TempStorage:Path包装到自己的配置类中,例如StorageProviderSettings
  • StorageProvider依赖于新的配置类。
  • 将配置类作为singleton注册到ASP.NET配置系统中。

示例:

public sealed class StorageProviderSettings
{
    public readonly string TempStoragePath;

    public StorageProviderSettings(string tempStoragePath)
    {
        if (string.IsNullOrWhiteSpace(tempStoragePath))
            throw new ArgumentException(nameof(tempStoragePath));
        this.TempStoragePath = tempStoragePath;
    }
}

public sealed class StorageProvider : IStorageProvider
{
    public StorageProvider(
        StorageProviderSettings settings, ILogger<StorageProvider> logger)
    {
        // ...
    }
}

// Registration
services.AddSingleton(new StorageProviderSettings(Configuration["TempStorage.Path"]));
services.AddSingleton<IStorageProvider, StorageProvider>();

答案 1 :(得分:0)

使用Tratcher在评论中建议的Options模式。请阅读official docs on Configuration

中的更多内容

基本上你定义一个类来保存你需要的值:

public class StorageProviderOptions
{
    public string TempStoragePath { get; set; }
}

然后在ConfigureServices中注册类型:

services.Configure<StorageProviderOptions>();

在您的代码中,您请求IOptions<StorageProviderOptions>并将其设置为StorageProviderOptions的实例:

public class SomeController
{
    private readonly StorageProviderOptions _options;

    public SomeController(IOptions<StorageProviderOptions> options)
    {
        _options = options.Value;
    }
}

最后,确保配置源中的元素与TempStoragePath名称匹配。或者,您可以使用代码

ConfigureServices中注册该选项
services.Configure<ServiceProviderOptions>(o => o.TempStoragePath = "temp");