Microsoft MVP성태의 닷넷 이야기
.NET Framework: 126.4. CAG - Unity 컨테이너 사용 [링크 복사], [링크+제목 복사],
조회: 27901
글쓴 사람
정성태 (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
정성태

... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11049정성태9/24/201620925오류 유형: 357. 윈도우 백업 시 오류 - 0x81000037
11048정성태9/24/201621940VC++: 100. 전역 변수 유형별 실행 파일 크기 차이점
11047정성태9/21/201625776기타: 61. algospot.com - 양자화(Quantization) 문제 [2]파일 다운로드1
11046정성태9/15/201627379개발 환경 구성: 298. Windows 10 - bash 실행 시 시작 디렉터리 자동 변경
11045정성태9/15/201620080Windows: 119. Windows 10 - bash 명령어 창을 실행했는데 바로 닫히는 경우
11044정성태9/15/201620314VS.NET IDE: 112. Visual Studio 확장 - 편집 화면 내에서 링크를 누르면 외부 웹 브라우저에서 열기
11043정성태9/15/201621718.NET Framework: 606. .NET 스레드 콜 스택 덤프 (7) - ClrMD(Microsoft.Diagnostics.Runtime)를 이용한 방법 [1]파일 다운로드1
11042정성태9/14/201619875오류 유형: 356. Unknown custom metadata item kind: 6
11041정성태9/10/201619363.NET Framework: 605. CLR4 보안 - yield 구문 내에서 SecurityCritical 메서드 사용 불가 - 2번째 이야기
11040정성태9/10/201626677.NET Framework: 604. C# Windows Forms - Drag & Drop 예제 코드 [2]파일 다운로드1
11039정성태9/9/201623182오류 유형: 355. Visual Studio 빌드 오류 - error CS0122: '__ComObject' is inaccessible due to its protection level
11038정성태9/9/201625028VC++: 99. 서로 다른 프로세스에서 WM_DROPFILES 메시지를 전송하는 방법파일 다운로드1
11037정성태9/8/201628259.NET Framework: 603. socket - shutdown 호출이 필요한 사례파일 다운로드1
11036정성태8/29/201624749개발 환경 구성: 297. 소스 코드가 없는 닷넷 어셈블리를 디버깅할 때 지역 변숫값을 확인하는 방법
11035정성태8/29/201620400오류 유형: 354. .NET Reflector - PDB 생성 화면에서 "Clear Store"를 하면 "Index and length must refer to a location within the string" 예외 발생
11034정성태8/25/201624423개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법 [2]
11033정성태8/24/201622256오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201621472개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201617728오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201620284VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201627414.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201621503오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201622567.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201623548Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201622252개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201621546오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...