我已经在.NET Framework 4.7.1中使用了新的Microsoft.Extensions库,主要包括DependencyInjection和Configuration库。
2.x版本的库与.NET Standard 2.0兼容,这意味着它们可以添加到任何与.NET Standard 2.0兼容的运行时应用程序中,例如.NET Framework 4.7.1及以上版本或.NET Core 2.0及以上版本。
在旧版运行时(4.6.1及更高版本),NuGet可能需要添加一些具有较新版本的某些系统程序集的额外软件包,例如System.Runtime。
你无法将2.0扩展包添加到4.6中。你可以添加旧版的1.x版本,这些版本用于.NET Core 1.x。
在.NET Core和完整框架中,配置扩展的方法是相同的:
你创建一个ConfigurationBuilder,添加配置提供程序,并在最后调用Build()以获取IConfigurationRoot
对象:
IConfigurationRoot configRoot = new ConfigurationBuilder()
.AddUserSecrets<Program>()
.AddJsonFile($"appsettings.json")
.Build();
创建一个ServiceCollection,注册服务并调用BuildServiceProvider()
来获取ServiceProvider
。您将使用该 ServiceProvider 创建需要注入的类的实例。
ASP.NET Core,也适用于完整的框架,提供额外的辅助库来隐藏样板代码。
IServiceCollection services = new ServiceCollection()
ServiceProvider provider= services.AddSingleton<MyService>()
.AddTransient<AnotherService>()
.AddTransient<ServiceThatNeedsTheOthers>()
.BuildServiceProvider()
假设第三个服务是:
public class ServiceThatNeedsTheOthers
{
public ServiceThatNeedsTheOthers(MyService s1,AnotherService s2){..}
}
您可以使用以下方式创建:
var service3=provider.GetRequiredService<ServiceThatNeedsTheOthers>()
所有这些内容都在Mark Michaelis的Essential .NET专栏中进行了描述,例如Dependency Injection with .NET Core和Configuration in .NET Core。这些文章展示了如何在需要编写所有样板代码的控制台应用程序中设置和使用扩展。
PS ASP.NET Core 2.0也可以瞄准完整框架。对于新的Web应用程序,创建一个针对4.7.1的ASP.NET Core 2.0项目可能是有意义的。
services.AddLogging(opt => opt.AddLog4Net("log4net.config"))
,非常感谢您的回答。 - fededim