1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WinUI 3 で DI

Last updated at Posted at 2025-06-30

はじめに

MAUIではMauiProgramクラスでMauiApp.CreateBuilder().Services.AddXXXしてDIできたので、WinUI3でもAppクラスにBuilderがあると思ったらなさそう。
というわけで、過去記事を参考にしてWinUI3でもDIします。

実装

App.xaml.cs
 public partial class App : Application
 {

     private static IHost? _host;

     protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
     {
         HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder();

         // DB(シングルトン)
         var _dbContext = new WinUI3DemoContext();
         _dbContext.Database.EnsureCreated();
         hostBuilder.Services.AddSingleton<WinUI3DemoContext>(_dbContext);

         // 画面(シングルトン)
         hostBuilder.Services.AddSingleton<MainWindow>();

         // ページ(毎回生成)
         hostBuilder.Services.AddTransient<No1View>();
         hostBuilder.Services.AddTransient<No2View>();
         hostBuilder.Services.AddTransient<No3View>();
         hostBuilder.Services.AddTransient<No4View>();

         _host = hostBuilder.Build();

         // メイン画面を取得
         var _mainWindow = _host.Services.GetService<MainWindow>()!;
         _mainWindow.Activate();
     }

     public static IHost Hosting
     {
         get => _host!;
     }
 }

ナビゲーション部分の実装

MainWindows.xaml.cs
private void naviView_SelectionChanged(NavigationView naviView, NavigationViewSelectionChangedEventArgs e)
{
    var selectedItem = e.SelectedItem;
    object tag = ((NavigationViewItem)selectedItem).Tag;
    if (tag as string == "No1View")
    {
        ContentView.Content = App.Hosting.Services.GetService<No1View>();
    }
    else if (tag as string == "No2View")
    {
        ContentView.Content = App.Hosting.Services.GetService<No2View>();
    }
    else if (tag as string == "No3View")
    {
        ContentView.Content = App.Hosting.Services.GetService<No3View>();
    }
    else if (tag as string == "No4View")
    {
        ContentView.Content = App.Hosting.Services.GetService<No4View>();
    }
    else
    {
        ContentView.Content = null;
    }
}

ページ側の実装

No4View.xaml.cs
public sealed partial class No4View : Page
{
    private WinUI3DemoContext dbContext;

    // DIされたいサービスをコンストラクタに記載
    public No4View(WinUI3DemoContext dbContext)
    {
        this.dbContext = dbContext;

        InitializeComponent();

        // ~略~

できました。
IHostedService作らなくてもいいでしょ?

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?