我正在创建一项需要一些配置参数和记录器的服务。这是我服务的构造函数:
public StorageProvider(string directory, ILogger<StorageProvider> logger)
我刚刚添加了记录器。我曾经在我的startup.cs中像这样初始化它:
services.AddSingleton<IStorageProvider>(
new StorageProvider(Configuration["TempStorage.Path"]));
directory
参数来自配置文件,记录器获取DI。如何设置IStorageProvider
?
答案 0 :(得分:2)
您应该执行以下操作:
TempStorage:Path
包装到自己的配置类中,例如StorageProviderSettings
。StorageProvider
依赖于新的配置类。示例:
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");