Microsoft MVP성태의 닷넷 이야기
.NET Framework: 126.4. CAG - Unity 컨테이너 사용 [링크 복사], [링크+제목 복사],
조회: 27957
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
부모글 보이기/감추기
(연관된 글이 2개 있습니다.)

Unity 컨테이너 사용


모듈까지 제작해서 끼워넣었으니, 이제 Unity를 전반적으로 활용해 보겠습니다.

23.3 CAG - 간단한 유형의 모듈 제작 
; https://www.sysnet.pe.kr/2/0/695

오늘의 내용은 다음의 글에서 설명된 내용을 정리한 것입니다.

How to: Register and Use Services
; https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ff921345(v=pandp.10)




지난 시간에는 모듈에서 IRegionManager를 받았었지만, 사실 거의 모든 모듈에서는 기본적으로 IUnityContainer 자체를 받고 싶어할 것입니다. 왜냐하면, IUnityContainer만 있다면 Unity 컨테이너에 등록된 모든 개체를 구해올 수 있기 때문인데요. 재미있는 것은 Unity Container 자체도 스스로에게 등록되어 있기 때문에 Unity 문맥에서 로드되는 Module에서 DI(Dependency Injection)로 다음과 같이 받을 수가 있습니다.

private readonly IUnityContainer unityContainer;

public StatusBarModule(IUnityContainer unityContainer)
{
    this.unityContainer = unityContainer;
}

이렇게 받은 것으로부터 IRegionManager를 다음과 같이 구할 수가 있겠지요.

private readonly IRegionManager regionManager;
private readonly IUnityContainer unityContainer;

public StatusBarModule(IUnityContainer unityContainer)
{
    this.unityContainer = unityContainer;
    this.regionManager = unityContainer.Resolve<IRegionManager>();
}

자, 그럼 동적 로드되는 Module에서 Application EXE에 정의된 Shell을 받아와 볼까요?
원칙적으로 볼 때, 동적 로드되는 모듈이 EXE 측을 직접 참조해서는 안됩니다. 따라서 Shell을 EXE 프로젝트를 참조함으로써 받아올 수는 없습니다.

어쩔 수 없지요. 그렇다면 별도의 인터페이스 모듈을 정의해서 Unity를 통해서 받아오면 될 것입니다.

이를 위해 "DevToolManager.CodeModel" 프로젝트를 새로 생성하고 IShell.cs 파일을 생성해서 다음과 같이 정의합니다.

==== IShell.cs ==== 

public interface IShell
{
    void Alert(string text);
    void Show();
}

DevToolManager 프로젝트에서는 DevToolManager.CodeModel 프로젝트를 참조하고, Shell.xaml.cs에서 IShell을 상속받아 다음과 같이 처리해 줍니다.

==== Shell.xaml.cs ==== 

public partial class Shell : Window, IShell
{
    public Shell()
    {
        InitializeComponent();
    }

    #region IShell Members

    public void Alert(string text)
    {
        MessageBox.Show(text);
    }

    #endregion
}
(IShell.Show 메서드가 정의되지 않았는데, 이는 Window 타입 자체에 이미 정의되어 있기 때문에 생략이 가능합니다.)

이것으로 Shell은 준비가 되었는데, 이제 이를 Unit Container에 알려야 합니다. 사실 어느 곳에서나 해도 상관없지만, Bootstrapper 클래스에서 이런 경우를 위해 다음과 같이 ConfigureContainer라는 가상 메서드를 제공해 주고 있으니 그걸 사용합니다.

public class Bootstrapper : UnityBootstrapper
{
    protected override DependencyObject CreateShell()
    {
        IShell shell = Container.Resolve<IShell>();
        shell.Show();
        return shell as DependencyObject;
    }

    protected override void ConfigureContainer()
    {
        Container.RegisterType<IShell, Shell>(new ContainerControlledLifetimeManager());

        base.ConfigureContainer();
    }

.... [중간 생략] ....
}

ConfigureContainer 가상 메서드에서 IShell 인터페이스로 Shell 구현 타입을 매핑시켜서 등록을 했고, CreateShell에서 곧바로 Resolve시켜서 IoC 컨테이너 - 즉 Unity 컨테이너로부터 Shell 인스턴스를 받아오고 있습니다. 이처럼, 모듈에서도 다음과 같이 받아올 수가 있습니다.

private readonly IRegionManager regionManager;
private readonly IShell shell;
private readonly IUnityContainer unityContainer;

public StatusBarModule(IUnityContainer unityContainer)
{
    this.unityContainer = unityContainer;

    this.shell = unityContainer.Resolve<IShell>();
    this.regionManager = unityContainer.Resolve<IRegionManager>();
}

이 정도만 해도, 벌써 Unity가 Prism 전반에서 어떻게 사용될 수 있을지 설명이 다 되는 것 같습니다. IoC 컨테이너로서, 원하는 타입을 RegisterType 또는 RegisterInstance로 등록하고 향후 Resolve 메서드를 통해서 구해오는 구조가 잡히고 있습니다. 물론, 그렇게 관리되는 타입들은 Unity의 문맥에서 활성화되어 Unity가 제공하는 DI 기능을 십분 활용할 수가 있게 됩니다.

하나 더 예를 들어서, StatusBarModule 타입에서 IShell을 다음과 같이 속성을 통해서도 할당되어질 수 있습니다

IShell shell;

[Dependency]
public IShell Shell
{
    set { this.shell = value; }
}

생성자의 경우에는 별다른 특성을 주지 않아도 인자 형식이 Unity 컨테이너에 등록된 타입이라면 자동으로 Injection을 시켜주지만, 속성의 경우에는 반드시 Dependency 특성과 setter를 갖춘 프로퍼티 형식이어야 DI 혜택을 받게 됩니다.

마지막으로,

지금까지는 완전히 분리된 모듈구조이기 때문에 인터페이스로 등록을 했지만, 만약 Module 내에서 등록되어야 할 타입이 있다면 구현 타입을 그대로 사용해도 무방합니다. 예를 들어, StatusBarModule에서 Region에 뷰를 등록하는 코드를 다음과 같이 수정할 수 있습니다.

public class StatusBarModule : IModule
{
    private readonly IRegionManager regionManager;

	... [중간 생략] ...

    public void Initialize()
    {
        unityContainer.RegisterType<DefaultStatusBar>();

        this.regionManager.Regions["StatusRegion"].Add(unityContainer.Resolve<DefaultStatusBar>());
    }
}

뷰의 경우, 그것이 정의된 모듈 이외의 다른 모듈에서 사용할 가능성은 많지 않습니다. View의 경우에 굳이 Unity에 등록할 필요가 없긴 하지만, 경우에 따라서 MVP(Model View Presenter)와 같은 구조를 취하는 경우 View와 Presenter에 대한 DI를 사용하기도 하기 때문에 위와 같은 식으로 모델 내에 정의되는 View 역시 Unity 컨테이너의 혜택을 받을 수 있도록 할 수 있습니다.

다운로드: 예제 솔루션




[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/17/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-01-28 05시03분
[.NET Conf 2021 x Seoul] 프리즘으로 합성 XAML 애플리케이션 만들기 (동영상 46분)
; https://www.youtube.com/watch?v=5Mitsg9D5Ok
정성태

... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
12036정성태10/14/201925467.NET Framework: 866. C# - 고성능이 필요한 환경에서 GC가 발생하지 않는 네이티브 힙 사용파일 다운로드1
12035정성태10/13/201919585개발 환경 구성: 461. C# 8.0의 #nulable 관련 특성을 .NET Framework 프로젝트에서 사용하는 방법 [2]파일 다운로드1
12034정성태10/12/201918904개발 환경 구성: 460. .NET Core 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 [1]
12033정성태10/11/201923114개발 환경 구성: 459. .NET Framework 프로젝트에서 C# 8.0/9.0 컴파일러를 사용하는 방법
12032정성태10/8/201919237.NET Framework: 865. .NET Core 2.2/3.0 웹 프로젝트를 IIS에서 호스팅(Inproc, out-of-proc)하는 방법 - AspNetCoreModuleV2 소개
12031정성태10/7/201916492오류 유형: 569. Azure Site Extension 업그레이드 시 "System.IO.IOException: There is not enough space on the disk" 예외 발생
12030정성태10/5/201923299.NET Framework: 864. .NET Conf 2019 Korea - "닷넷 17년의 변화 정리 및 닷넷 코어 3.0" 발표 자료 [1]파일 다운로드1
12029정성태9/27/201924124제니퍼 .NET: 29. Jennifersoft provides a trial promotion on its APM solution such as JENNIFER, PHP, and .NET in 2019 and shares the examples of their application.
12028정성태9/26/201919088.NET Framework: 863. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상을 해결하기 위한 시도파일 다운로드1
12027정성태9/26/201914815오류 유형: 568. Consider app.config remapping of assembly "..." from Version "..." [...] to Version "..." [...] to solve conflict and get rid of warning.
12026정성태9/26/201920234.NET Framework: 862. C# - Active Directory의 LDAP 경로 및 정보 조회
12025정성태9/25/201918542제니퍼 .NET: 28. APM 솔루션 제니퍼, PHP, .NET 무료 사용 프로모션 2019 및 적용 사례 (8) [1]
12024정성태9/20/201920461.NET Framework: 861. HttpClient와 HttpClientHandler의 관계 [2]
12023정성태9/18/201920927.NET Framework: 860. ServicePointManager.DefaultConnectionLimit와 HttpClient의 관계파일 다운로드1
12022정성태9/12/201924867개발 환경 구성: 458. C# 8.0 (Preview) 신규 문법을 위한 개발 환경 구성 [3]
12021정성태9/12/201940673도서: 시작하세요! C# 8.0 프로그래밍 [4]
12020정성태9/11/201923842VC++: 134. SYSTEMTIME 값 기준으로 특정 시간이 지났는지를 판단하는 함수
12019정성태9/11/201917400Linux: 23. .NET Core + 리눅스 환경에서 Environment.CurrentDirectory 접근 시 주의 사항
12018정성태9/11/201916196오류 유형: 567. IIS - Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. (D:\lowSite4\web.config line 11)
12017정성태9/11/201920018오류 유형: 566. 비주얼 스튜디오 - Failed to register URL "http://localhost:6879/" for site "..." application "/". Error description: Access is denied. (0x80070005)
12016정성태9/5/201920016오류 유형: 565. git fetch - warning: 'C:\ProgramData/Git/config' has a dubious owner: '(unknown)'.
12015정성태9/3/201925427개발 환경 구성: 457. 윈도우 응용 프로그램의 Socket 연결 시 time-out 시간 제어
12014정성태9/3/201919186개발 환경 구성: 456. 명령행에서 AWS, Azure 등의 원격 저장소에 파일 관리하는 방법 - cyberduck/duck 소개
12013정성태8/28/201922087개발 환경 구성: 455. 윈도우에서 (테스트) 인증서 파일 만드는 방법 [3]
12012정성태8/28/201926645.NET Framework: 859. C# - HttpListener를 이용한 HTTPS 통신 방법
12011정성태8/27/201926230사물인터넷: 57. C# - Rapsberry Pi Zero W와 PC 간 Bluetooth 통신 예제 코드파일 다운로드1
... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...