Search code examples
asp.net-corenuget-packageusing-directives

.Net Core: Using Directive Without Adding Package?


For example this happened to me when I added configuration (IConfigurationRoot) in the Startup.cs file, to be able to access appsettings.json file which has a connection string.

So the first time I write IConfigurationRoot it is obviously marked as not recognized, so I put my mouse over it and expand the Visual Studio suggestions from the light bulb, which are:

  • using Microsoft.Extension.Configuration:
  • Microsoft.Extension.Configuration.IConfigurationRoot
  • Generate Type
  • Add package Microsoft.Extension.Configuration.Abstractions 1.1.0

So if I pick "using Microsoft.Extensions.Configuration",a using directive is added at the top of my file and VS recognices IConfigurationRoot, everything works fine. But checking the References in my project, this library was not added to it:

No Reference Added

So if instead of picking the using directive, I pick "Add package Microsoft.Extensions.Configuration.Abstractions 1.1.0", Visual Studio also adds the using directive but additionally it adds a new Reference:

Reference Added

I'm not understanding why this happens, why adding the using directive (first suggestion) works fine, is it because the reference is already contained in another library?, if so, why should I add the package individually?. Is it better to add it individually?, what happens if I do, am I adding a reference to the same library twice?

Thanks in advance.


Solution

  • ...is it because the reference is already contained in another library?

    Yes, look under the Microsoft.Extensions.Configuration.FileExtensions or Microsoft.Extensions.Configuration.Json and you eventually get to the Abstractions package.

    If so, why should I add the package individually?

    There is no need. The light bulb tooling might not quite up to speed with the whole package dependency stuff.

    Is it better to add it individually?

    Not really, but if your ever removed some of those base package then adding it individually from Nuget would ensure that it would remain.

    What happens if I do, am I adding a reference to the same library twice?

    In an indirect way, yes, but there's no harm. The Dependency tree view drills down into each layer of dependencies. You will see lots of "duplicates" if start expanding those nodes.