gpt4 book ai didi

c# - 为我自己的类库创建选项类

转载 作者:行者123 更新时间:2023-11-30 17:25:10 24 4
gpt4 key购买 nike

我在一个类库中工作,该类库根据用户在 Setup.cs 中设置的配置执行某些操作(我仍然不知道哪种方法更适合,ConfigureConfigureServices)。

很快,我的库将在 nuget 中,用户将可以安装和配置它。问题是,如何创建该选项/配置类,在 Startup.cs(ConfigureConfigureServices)中实例化该类并将该选项传递给我的类/lib/包?

这是我在实践中的疑问:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddMyLib(s => s.Value = 1);
}

在我的类库/nuget 包中

public class CalculationHelper
{
public bool GetSomething()
{
if (Options.Value == 1)
return true;

return false;
}
}

在扩展方法(DI)中

public static void AddMyLib(this IServiceCollection app, Action<Options> options = null)
{
// Here in this Extension method, I need save this options that I can retrieve for my class library (CalculationHelper).
}

我见过很多使用这种配置方法的库,比如 Swagger、AutoMapper、Serilog 等。

这就是我能详细说明的,希望你能理解。

最佳答案

假设

public class YourOptions {
public int Value { get; set; } = SomeDefaultValue;
}

public class YourService : IYourService {
private readonly YourOptions options;

public YourService (YourOptions options) {
this.options = options;
}

public bool GetSomething() {
if (options.Value == 1)
return true;

return false;
}
}

创建允许在添加服务时配置选项的扩展方法。

public static class MyLibServiceCollectionExtensions {
public static IServiceCollection AddMyLib(this IServiceCollection services,
Action<YourOptions> configure = null) {
//add custom options and allow for it to be configured
if (configure == null) configure = o => { };
services.AddOptions<YourOptions>().Configure(configure);
services.AddScoped(sp => sp.GetRequiredService<IOptions<YourOptions>>().Value);

//...add other custom service for example
services.AddScoped<IYourService, YourService>();

return services;
}
}

您的图书馆的用户随后将根据需要进行配置

public void ConfigureServices(IServiceCollection services) {

services.AddMyLib(options => options.Value = 1);

//...
}

以及在使用您的服务时

public SomeClass(IYourService service) {
bool result = service.GetSomething();
}

是的,标准做法是使用 IOptions<T> .我个人不喜欢注入(inject)它,并且倾向于使用上面建模的模式。我仍然为那些仍想使用它的人注册它。

关于c# - 为我自己的类库创建选项类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59186563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com