在WPF中使用.NET Core 3.0依賴項注入和服務提供程序

前言

咱們都知道.NET Core提供了對依賴項注入的內置支持。咱們一般在ASP.NET Core中使用它(從Startup.cs文件中的ConfigureServices方法開始),可是該功能不限於此框架,咱們能夠在WPF和Windows Forms應用程序中使用它。git

實踐

  1. 新建項目

    1572333532.jpg

  2. 將所需的NuGet包添加到項目中。

    • Microsoft.Extensions.DependencyInjection
    • Microsoft.Extensions.Options.ConfigurationExtensions
    • Microsoft.Extensions.Configuration.Json 1572334178_1_.jpg
  3. 而後,將一個名爲appsettings.json的文件添加到項目的根文件夾。將其「 構建操做」屬性設置爲「 內容」,將「複製到輸出目錄」設置爲「 複製」(若是較新):

    {
    "AppSettings": {
        "AppName": "SampleNetCore3WpfDependencyInjection"
        }
    }
  4. 建立一個AppSettings.cs文件來保存配置設置。該文件將映射咱們在appsettings.json中編寫的設置:

    public class AppSettings
        {
            public string AppName { get; set; } 
        }
  5. 建立一個示例服務:

    public interface ISampleService
        {
            Task<string> GetCurrentDate();
        }
    public class SampleService : ISampleService
        {
            public async Task<string> GetCurrentDate() => 
            await Task.FromResult(DateTime.Now.ToLongDateString());
        }

    而後像往常同樣在IOC容器中註冊服務:github

    services.AddScoped<ISampleService, SampleService>();
  6. 打開App.xaml文件並刪除Application類的StartupUri屬性。而後,咱們須要重寫App.xaml.cs中的OnStartup方法:

    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));
            }
        }
  7. MainWindow簡單佈局及代碼改造

    如上所述,MainWindow位於IOC容器中。所以,當咱們從服務提供商處得到服務時,它將自動注入全部必需的服務(若是有)。:json

    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}";
            }
        }

    1572335382_1_.jpg

  8. Demo地址:githubapp

相關文章
相關標籤/搜索