标签:provider iter amp string rom config over tar long
原文:在WPF中使用.NET Core 3.0依赖项注入和服务提供程序
我们都知道.NET Core提供了对依赖项注入的内置支持。我们通常在ASP.NET Core中使用它(从Startup.cs文件中的ConfigureServices方法开始),但是该功能不限于此框架,我们可以在WPF和Windows Forms应用程序中使用它。
{
"AppSettings": {
"AppName": "SampleNetCore3WpfDependencyInjection"
}
}
public class AppSettings
{
public string AppName { get; set; }
}
public interface ISampleService
{
Task<string> GetCurrentDate();
}
public class SampleService : ISampleService
{
public async Task<string> GetCurrentDate() =>
await Task.FromResult(DateTime.Now.ToLongDateString());
}
然后像往常一样在IOC容器中注册服务:
services.AddScoped<ISampleService, SampleService>();
public partial class App : Application
{
public IServiceProvider ServiceProvider { get; private set; }
public IConfiguration Configuration { get; private set; }
protected override void OnStartup(StartupEventArgs e)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
Configuration = builder.Build();
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
ServiceProvider = serviceCollection.BuildServiceProvider();
var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
mainWindow.Show();
}
private void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection(nameof(AppSettings)));
services.AddScoped<ISampleService, SampleService>();
services.AddTransient(typeof(MainWindow));
}
}
如上所述,MainWindow位于IOC容器中。因此,当我们从服务提供商处获得服务时,它将自动注入所有必需的服务(如果有)。:
public partial class MainWindow : Window
{
private readonly ISampleService sampleService;
private readonly AppSettings settings;
public MainWindow(ISampleService sampleService,
IOptions<AppSettings> settings)
{
InitializeComponent();
this.sampleService = sampleService;
this.settings = settings.Value;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var serviceData =await sampleService.GetCurrentDate();
var settingsData = settings;
TextBox1.Text = $"serviceData:{serviceData}{Environment.NewLine}settingsData:{settings.AppName}";
}
}
Demo地址:github
在WPF中使用.NET Core 3.0依赖项注入和服务提供程序
标签:provider iter amp string rom config over tar long
原文地址:https://www.cnblogs.com/lonelyxmas/p/11763767.html