logo MSJO.kr

WPF Dependency Injection

2021-09-06
MsJ
   

기본적으로 ASP.NET Core는 클래스와 해당 종속성 간의 IoC(Inversion of Control)를 실현하는 기술인 DI(종속성 주입) 소프트웨어 디자인 패턴을 지원1한다.

Desktop 애플리케이션 개발에 자주 사용하는 WPF는 개발자가 직접 작성하여 추가하거나 또는 MVVM 패턴을 지원하는 Caliburn.Micro2와 같은 프레임워크를 사용하여 DI(종속성 주입) 환경을 구축한다.

WPF를 이용한 개발에 DI를 적용하는 기본적인 환경 구성을 Microsoft.Extensions.Hosting 패키지를 이용(IHost Interface3)하여 구축할 수 있다.

App.xaml
<Application x:Class="ExamHelloDI.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!-- StartupUri="MainWindow.xaml" : 기본값 제거-->
    <Application.Resources>
    </Application.Resources>
</Application>
App.xaml.cs
using ExamHelloDI.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Windows;

namespace ExamHelloDI
{
    public partial class App
    {
        private readonly IHost _host;

        public App()
        {
            _host = Host.CreateDefaultBuilder().ConfigureServices((context, services) =>
            {
                context.HostingEnvironment.ApplicationName = "ExamHelloDI";
                ConfigureServices(services);
            }).Build();
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<MainWindow>();
            services.AddTransient<IDateTimeServices, DateTimeServices>();
        }

        protected override async void OnStartup(StartupEventArgs e)
        {
            await _host.StartAsync();
            _host.Services.GetRequiredService<MainWindow>().Show();
            base.OnStartup(e);
        }

        protected override async void OnExit(ExitEventArgs e)
        {
            using (_host)
            {
                await _host.StopAsync();
            }
            base.OnExit(e);
        }
    }
}
MainWindow.xaml
<Window x:Class="ExamHelloDI.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        xmlns:local="clr-namespace:ExamHelloDI"
        d:DataContext="{d:DesignInstance local:MainWindow, IsDesignTimeCreatable=True}"
        Title="MainWindow" Height="300" Width="500">

    <Grid>
        <TextBox Grid.Row="0" Text="{Binding DateTime, Mode=OneWay}" />
    </Grid>
</Window>
MainWindow.xaml.cs
using ExamHelloDI.Services;

namespace ExamHelloDI
{
    public partial class MainWindow
    {
        private readonly IDateTimeServices _dateTimeServices;

        public MainWindow(IDateTimeServices dateTimeServices)
        {
            InitializeComponent();

            _dateTimeServices = dateTimeServices;
            DataContext = this;
        }

        public string DateTime => _dateTimeServices.GetDateTimeString();
        // set { } Mode=OneWay
    }
}
IDateTimeServices.cs
namespace ExamHelloDI.Services
{
    public interface IDateTimeServices
    {
        string GetDateTimeString();
    }
}
DateTimeServices.cs
using System;

namespace ExamHelloDI.Services
{
    public class DateTimeServices : IDateTimeServices
    {
        public string GetDateTimeString()
        {
            return DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        }
    }
}

예제에 사용한 소스 코드는 Codewrinkles, “Adding Dependency Injection to WPF applications” 강좌를 참고하여 작성하였다.

Reference
  1. docs.microsoft.com, “ASP.NET Core에서 종속성 주입”
  2. github.com, “Caliburn.Micro”
  3. docs.microsoft.com, “IHost Interface”

Prεv(Θld)   Nεxt(Nεw)
Content RustLang.kr
Search     RSS Feed     BY-NC-ND