简化的IOptions方法<T>

mmi*_*mix 8 dependency-injection asp.net-core .net-4.7.1 asp.net-core-2.1

我正在尝试使用内置DI机制获得符合ASP.NET Core 2.1应用程序的.NET Framework类库.现在,我创建了一个配置类,并在appsettings.json中添加了相应的部分:

services.Configure<MyConfig>(Configuration.GetSection("MyConfiguration"));
services.AddScoped<MyService>();
Run Code Online (Sandbox Code Playgroud)

在类lib中:

public class MyService 
{
    private readonly MyConfig _config;

    public MyService(IOptions<MyConfig> config)
    {
        _config = config.Value;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,为了构建这个classlib,我必须添加Microsoft.Extensions.OptionsNuGet包.问题是,程序包带有很多依赖项,看起来相当过分,只是为了一个接口而添加.

在此输入图像描述

因此,最终的问题是,"我可以采用另一种方法来配置位于.NET Framework类库中的DI服务吗?

小智 5

查看由Filip Wojcieszyn撰写的这篇文章。

https://www.strathweb.com/2016/09/strong-typed-configuration-in-asp-net-core-without-ioptionst/

您添加扩展方法:

public static class ServiceCollectionExtensions
{
    public static TConfig ConfigurePOCO<TConfig>(this IServiceCollection services, IConfiguration configuration) where TConfig : class, new()
    {
        if (services == null) throw new ArgumentNullException(nameof(services));
        if (configuration == null) throw new ArgumentNullException(nameof(configuration));

        var config = new TConfig();
        configuration.Bind(config);
        services.AddSingleton(config);
        return config;
    }
}
Run Code Online (Sandbox Code Playgroud)

在配置中应用它:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.ConfigurePOCO<MySettings>(Configuration.GetSection("MySettings"));
}
Run Code Online (Sandbox Code Playgroud)

然后使用它:

public class DummyService
{
    public DummyService(MySettings settings)
    {
        //do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)