Microsoft MVP성태의 닷넷 이야기
.NET Framework: 126.4. CAG - Unity 컨테이너 사용 [링크 복사], [링크+제목 복사],
조회: 27969
글쓴 사람
정성태 (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)
11786정성태11/29/201818634오류 유형: 505. OpenGL.NET 예제 실행 시 "Managed Debugging Assistant 'CallbackOnCollectedDelegate'" 예외 발생
11785정성태11/21/201820981디버깅 기술: 120. windbg 분석 사례 - ODP.NET 사용 시 Finalizer에서 System.AccessViolationException 예외 발생으로 인한 비정상 종료
11784정성태11/18/201820243Graphics: 32. .NET으로 구현하는 OpenGL (7), (8) - Matrices and Uniform Variables, Model, View & Projection Matrices파일 다운로드1
11783정성태11/18/201818366오류 유형: 504. 윈도우 환경에서 docker가 설치된 컴퓨터 간의 ping IP 주소 풀이 오류
11782정성태11/18/201817460Windows: 152. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선순위 조정 기능 - 두 번째 이야기
11781정성태11/17/201820838개발 환경 구성: 422. SFML.NET 라이브러리 설정 방법 [1]파일 다운로드1
11780정성태11/17/201821887오류 유형: 503. vcpkg install bzip2 빌드 에러 - "Error: Building package bzip2:x86-windows failed with: BUILD_FAILED"
11779정성태11/17/201822748개발 환경 구성: 421. vcpkg 업데이트 [1]
11778정성태11/14/201820072.NET Framework: 803. UWP 앱에서 한 컴퓨터(localhost, 127.0.0.1) 내에서의 소켓 연결
11777정성태11/13/201820532오류 유형: 502. Your project does not reference "..." framework. Add a reference to "..." in the "TargetFrameworks" property of your project file and then re-run NuGet restore.
11776정성태11/13/201818568.NET Framework: 802. Windows에 로그인한 계정이 마이크로소프트의 계정인지, 로컬 계정인지 알아내는 방법
11775정성태11/13/201820373Graphics: 31. .NET으로 구현하는 OpenGL (6) - Texturing파일 다운로드1
11774정성태11/8/201818806Graphics: 30. .NET으로 구현하는 OpenGL (4), (5) - Shader파일 다운로드1
11773정성태11/7/201818479Graphics: 29. .NET으로 구현하는 OpenGL (3) - Index Buffer파일 다운로드1
11772정성태11/6/201820425Graphics: 28. .NET으로 구현하는 OpenGL (2) - VAO, VBO파일 다운로드1
11771정성태11/5/201819458사물인터넷: 56. Audio Jack 커넥터의 IR 적외선 송신기 - 두 번째 이야기 [1]
11770정성태11/5/201827838Graphics: 27. .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리 [3]파일 다운로드1
11769정성태11/5/201818832오류 유형: 501. 프로젝트 msbuild Publish 후 connectionStrings의 문자열이 $(ReplacableToken_...)로 바뀌는 문제
11768정성태11/2/201819317.NET Framework: 801. SOIL(Simple OpenGL Image Library) - Native DLL 및 .NET DLL 제공
11767정성태11/1/201820204사물인터넷: 55. New NodeMcu v3(ESP8266)의 IR LED (적외선 송신) 제어파일 다운로드1
11766정성태10/31/201822310사물인터넷: 54. 아두이노 환경에서의 JSON 파서(ArduinoJson) 사용법
11765정성태10/26/201819201개발 환경 구성: 420. Visual Studio Code - Arduino Board Manager를 이용한 사용자 정의 보드 선택
11764정성태10/26/201824102개발 환경 구성: 419. MIT 라이선스로 무료 공개된 Detours API 후킹 라이브러리 [2]
11763정성태10/25/201821030사물인터넷: 53. New NodeMcu v3(ESP8266)의 https 통신
11762정성태10/25/201821461사물인터넷: 52. New NodeMCU v3(ESP8266)의 http 통신파일 다운로드1
11761정성태10/25/201821431Graphics: 26. 임의 축을 기반으로 3D 벡터 회전파일 다운로드1
... 76  77  78  79  80  81  82  83  84  85  [86]  87  88  89  90  ...