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

标签 c# asp.net .net-core

我在一个类库中工作,该类库根据用户在 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/

相关文章:

c# - 无法导入外部原型(prototype)文件 - 在命令行中工作但在 .net core 3 RC1 中不工作

c# - 如何在 MVC3 上禁止返回 403 上的正确消息?

.net - SqlMembershipProvider 与自定义解决方案

c# - .NET 核心 : HttpClientFactory: How to configure ConfigurePrimaryHttpMessageHandler without dependency injection?

asp.net - IIS ApplicationPoolIdentity没有对 'Temporary ASP.NET Files'的写权限

asp.net - 仅对单个按钮进行字段验证

c# - Azure 配置应用程序设置中的字典

C# 和 Microsoft Speech.Recognition 和 Speech.Synthesis

c# - 为什么提供 String(char[]) 的隐式运算符不好?

c# - 方法调用期间是否会发生上下文切换?