咱們都知道.NET Core提供了對依賴項注入的內置支持。咱們一般在ASP.NET Core中使用它(從Startup.cs文件中的ConfigureServices方法開始),可是該功能不限於此框架,咱們能夠在WPF和Windows Forms應用程序中使用它。git
{ "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容器中註冊服務:github
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容器中。所以,當咱們從服務提供商處得到服務時,它將自動注入全部必需的服務(若是有)。: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}"; } }
Demo地址:githubapp