Microsoft MVP성태의 닷넷 이야기
.NET Framework: 126.4. CAG - Unity 컨테이너 사용 [링크 복사], [링크+제목 복사],
조회: 29318
글쓴 사람
정성태 (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)
11257정성태7/31/201719881.NET Framework: 667. bypassTrustedAppStrongNames 옵션 설명파일 다운로드1
11256정성태7/25/201721818디버깅 기술: 90. windbg의 lm 명령으로 보이지 않는 .NET 4.0 ClassLibrary를 명시적으로 로드하는 방법 [1]
11255정성태7/18/201724320디버깅 기술: 89. Win32 Debug CRT Heap Internals의 0xBAADF00D 표시 재현 [1]파일 다운로드3
11254정성태7/17/201720747개발 환경 구성: 322. "Visual Studio Emulator for Android" 에뮬레이터를 "Android Studio"와 함께 쓰는 방법
11253정성태7/17/201721379Math: 21. "Coding the Matrix" 문제 2.5.1 풀이 [1]파일 다운로드1
11252정성태7/13/201719114오류 유형: 411. RTVS 또는 PTVS 실행 시 Could not load type 'Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowFactory2'
11251정성태7/13/201718600디버깅 기술: 88. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 (2)
11250정성태7/13/201722201디버깅 기술: 87. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 [1]
11249정성태7/12/201719919오류 유형: 410. LoadLibrary("[...].dll") failed - The specified procedure could not be found.
11248정성태7/12/201726491오류 유형: 409. pip install pefile - 'cp949' codec can't decode byte 0xe2 in position 208687: illegal multibyte sequence
11247정성태7/12/201720792오류 유형: 408. SqlConnection 객체 생성 시 무한 대기 문제파일 다운로드1
11246정성태7/11/201718852VS.NET IDE: 118. Visual Studio - 다중 폴더에 포함된 파일들에 대한 "Copy to Output Directory"를 한 번에 설정하는 방법
11245정성태7/10/201724619개발 환경 구성: 321. Visual Studio Emulator for Android 소개 [2]
11244정성태7/10/201724804오류 유형: 407. Visual Studio에서 ASP.NET Core 실행할 때 dotnet.exe 프로세스의 -532462766 오류 발생 [1]
11243정성태7/10/201721582.NET Framework: 666. dotnet.exe - 윈도우 운영체제에서의 .NET Core 버전 찾기 규칙
11242정성태7/8/201721108제니퍼 .NET: 27. 제니퍼 닷넷 적용 사례 (7) - 노후된 스토리지 장비로 인한 웹 서비스 Hang (멈춤) 현상
11241정성태7/8/201719772오류 유형: 406. Xamarin 빌드 에러 XA5209, APT0000
11240정성태7/7/201723577.NET Framework: 665. ClickOnce를 웹 브라우저를 이용하지 않고 쿼리 문자열을 전달하면서 실행하는 방법 [3]파일 다운로드1
11239정성태7/6/201724219.NET Framework: 664. Protocol Handler - 웹 브라우저에서 데스크톱 응용 프로그램을 실행하는 방법 [5]파일 다운로드1
11238정성태7/6/201721730오류 유형: 405. NT 서비스 시작 시 "Error 1067: The process terminated unexpectedly." 오류 발생 [2]
11237정성태7/5/201723405.NET Framework: 663. C# - PDB 파일 경로를 PE 파일로부터 얻는 방법파일 다운로드1
11236정성태7/4/201727117.NET Framework: 662. C# - VHD/VHDX 가상 디스크를 마운트하지 않고 파일을 복사하는 방법파일 다운로드1
11235정성태6/29/201721315Math: 20. Matlab/Octave로 Gram-Schmidt 정규 직교 집합 구하는 방법
11234정성태6/29/201718817오류 유형: 404. SharePoint 2013 설치 과정에서 "The username is invalid The account must be a valid domain account" 오류 발생
11233정성태6/28/201718711오류 유형: 403. SharePoint Server 2013을 Windows Server 2016에 설치할 때 .NET 4.5 설치 오류 발생
11232정성태6/28/201719622Windows: 144. Windows Server 2016에 Windows Identity Extensions을 설치하는 방법
... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...