Simplified approach to IOptions<T>

  • A+
Category:Languages

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.

Simplified approach to IOptions<T>

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?

 


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 configuration dependency in startup.cs and adjust the service's constructor accordingly:

var myConfiguration = Configuration.Value<MyConfiguration>("MyConfiguration");  services.AddTransient<MyService>(() => {     return new MyService(myConfiguration); }); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: