10

I am trying to get a .NET Framework class library in line with an ASP.NET Core 2.1 application while using builtin DI mechanism. Now, I created a config class and added appropriate section to appsettings.json:

services.Configure<MyConfig>(Configuration.GetSection("MyConfiguration"));
services.AddScoped<MyService>();

In class lib:

public class MyService 
{
    private readonly MyConfig _config;

    public MyService(IOptions<MyConfig> config)
    {
        _config = config.Value;
    }
}

However, in order to build this classlib I have to add Microsoft.Extensions.Options NuGet package. The problem is that package carries a hell of a lot of dependencies which seem rather excessive to add just for the sake of one interface.

enter image description here

So, the question ultimately is, "is there another approach I can take to configure a DI service located in .NET Framework class library which is not dependency heavy?

16
  • 1
    Without losing the scoped/reloadable features of the MS Configuration? No. If you are happy with static singleton options, you can register the options class with the IoC container. But you won't get new configuration when it changes and it won't be scoped (it could be changed in mid request if another requests modifies it)
    – Tseng
    Aug 17, 2018 at 11:40
  • 6
    The dependencies by itself aren't anything bad btw. Its the way .NET Core and .NET Standard were designed upon. Before you would have the big fat framework with all the assemblies shipped with it. In .NET Core/.NET Standard, its split among packages, that's the reason you see it. Also System.Memory contains important optimizations to reduce memory allocations and memory fragmentation, so its a good thing :P
    – Tseng
    Aug 17, 2018 at 11:46
  • 1
    Well this tone is not going to bring you any further. Like I said, if you don't care for the scoped options guarantees and the reloading mechanism, you can just inject MyConfig into your services instead of IOptions<MyConfig> and have an additional registration in ConfigureServices: services.AddScope<MyConfig>(provider => provider.GetRequiredService<IOptions<MyConfig>>().Value); instead. But .NET Core and .NET Standard is pretty mature by now, platform independent and can be used in a lot of enterprise scenarios (unless you need WCF or System.Web based stuff)
    – Tseng
    Aug 17, 2018 at 12:46
  • 1
    We do use f/w, but asp.net has moved completely to core. So no choice there, we either forsake web or we use core. No more TLC from MS for .NET :). And core is not mature, it has breaking changes between minor versions. Its far from being a rounded, well designed product. We hope that's why they took the 3.0 to go out next year, maybe someone finally realized this chaos is counter productive and decided to stabilize things. The mere fact we now have two competing .net products from the same company is disconcerting enough. The fact its done by the same people is, well, slightly schizophrenic.
    – mmix
    Aug 17, 2018 at 14:21
  • 1
    I have to ask because I find this fascinating, which dependencies are the problem?
    – davidfowl
    Aug 20, 2018 at 6:15

3 Answers 3

7

Check this article written by Filip Wojcieszyn.

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

You add extension method:

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;
    }
}

Apply it in configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.ConfigurePOCO<MySettings>(Configuration.GetSection("MySettings"));
}

And then use it:

public class DummyService
{
    public DummyService(MySettings settings)
    {
        //do stuff
    }
}
2
  • 1
    Actually, I solved the problem by appplying Bind in ConfigureServices, but I see the appeal and clarity in making that an extension on IServiceCollection, I am actually going to refactor it using this approach, so I'll also accept your answer.
    – mmix
    Aug 23, 2018 at 7:52
  • There is literally no need for any of this code. The IServiceCollection will handle the casting of the configuration section, exactly as outlined in my answer below. Traditionally the null check for services is done at the consumer level (i.e. the constructor) so I don't see the value added here.
    – pim
    Aug 24, 2018 at 9:26
1

I bumped into this problem a little while ago, if you can even call it a problem really. I think we all tend to get a little shell-shocked when we see a dependency list like that. But as @Tseng mentioned, it's really not a big deal to include a bunch of extra tiny assemblies (they'll be included in the bin already anyways by virtue of a reference in another project). But I will admit it's annoying to have to include them just for the options interface.

How I solved it was by resolving the service dependency in startup.cs and adjust the service's constructor accordingly:

services.AddTransient<MyService>(Configuration.GetConfiguration("MyConfiguration"));
2
  • The problem I have is not so much being shell shocked, its that these libraries are not solely asp.net libraries, they are also shared by WPF projects and a lot by legacy WinForms. Putting these dependencies in business classes makes no sense to us as they will then become dependencies of those other projects.
    – mmix
    Aug 23, 2018 at 7:47
  • I feel you and totally agree. I like to build my services with dependencies that can be considered the lowest possible denominator. Hence, why I like the injection of MyConfiguration directly over IOptions<MyConfiguration>.
    – pim
    Aug 23, 2018 at 9:39
0

If you don't care about whatever IOptions provides you, why not just inject IConfiguration into your service?

public class MyService
{
    private readonly IConfiguration _config;

    public MyService(IConfiguration config)
    {
        _config = config;
    }

    public void DoSomething()
    {
        var value = _config["SomeKey"];

        // doing something
    }
}
3
  • 6
    I would say that injecting IConfiguration is even worse than injecting IOption<T>. It's the Service Locator equivalent for configuration values, since it completely hides the used configuration values instead of explicitly stating them in te constructor. It makes the class responsible of reading and converting those values instead of the application's start-up path. I would even go as far as calling the injection of IConfiguration (any any class that lives outside the Composition Root) an anti-pattern.
    – Steven
    Aug 21, 2018 at 12:48
  • I would agree with the comment. Also, the IConfiguration is also an unneeded dependency that carries other stuff with it.
    – mmix
    Aug 23, 2018 at 7:45
  • Besides injecting IConfiguration and additional logic behind you could put into a class, the problem is configuration keys. In case of simple structure you could have var value = _config["SomeKey"];, but in more complicated configuration you might end up with var value = _config["ParentKey:ChildKey:ChildKey"]; Aug 25, 2018 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.