I'm already using the new Microsoft.Extensions libraries in .NET Framework 4.7.1, mainly the DependencyInjection and Configuration libraries.
The 2.x libraries are compatible with .NET Standard 2.0, which means they can be added to applications that target any runtime that is compatible with .NET Standard 2.0, ie .NET Framework 4.7.1 and above or .NET Core 2.0 and above.
In older runtimes (4.6.1 and later), NuGet may have to add some extra packages with newer versions of some system assemblies, eg System.Runtime.
You can't add the 2.0 Extension packages to 4.6 at all. You can add the older, 1.x versions which are use in .NET Core 1.x.
Configuring the extensions is done in the same way in .NET Core and Full Framework:
You create a ConfigurationBuilder, add configuration providers and call Build() in the end to get an IConfigurationRoot
object:
IConfigurationRoot configRoot = new ConfigurationBuilder()
.AddUserSecrets<Program>()
.AddJsonFile($"appsettings.json")
.Build();
Create a ServiceCollection, register services and call BuildServiceProvider()
to get a ServiceProvider
. You'll use that ServiceProvider to create instances of classes that require injection.
ASP.NET Core, which also works on the Full framework provides extra helper libraries that hide the boilerplate code.
IServiceCollection services = new ServiceCollection();
ServiceProvider provider= services.AddSingleton<MyService>()
.AddTransient<AnotherService>()
.AddTransient<ServiceThatNeedsTheOthers>()
.BuildServiceProvider();
Assuming the third service is :
public class ServiceThatNeedsTheOthers
{
public ServiceThatNeedsTheOthers(MyService s1,AnotherService s2){..}
}
You can create it with :
var service3=provider.GetRequiredService<ServiceThatNeedsTheOthers>();
All this is described in Mark Michaelis' Essential .NET column in MSDN Magazine, eg Dependency Injection with .NET Core and Configuration in .NET Core. The articles show how to setup and use the Extensions in Console applications where you need to write all the boilerplate.
PS ASP.NET Core 2.0 can target the Full framework too. For a new web application it may make sense to create an ASP.NET Core 2.0 project targeting 4.7.1