jae ung shin
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # DependencyContainer 이 패키지는 **AFToastView**, **SwiftSimpleAlertController**, **AFUserSession**과 같이 아직 모듈화 되어있지 않아서 AfreecaTV 프로젝트에 코드 의존성을 가져야 하는 상황을 해결하기 위해 생성한 패키지입니다. 기본적인 구조는 [링크](https://minsone.github.io/programming/swift-solved-circular-dependency-from-dependency-injection-container)를 참고하였습니다. ![struct](/uploads/e58c09b1f6762108caacb46298f633df/struct.png) 해당 패키지를 사용할 시 의존성 구조는 위와 같이 그려집니다. # 내부 구성 DependencyContainer에는 주입될 기능이 Conform해야 할 Injectable 프로토콜과 이러한 기능들을 Dictionary로 관리하는 Container가 존재합니다. ### Injectable ```swift public protocol Injectable { init() var id: String { get } func resolve() -> AnyObject } ``` Injectable 프로토콜 내부는 위와 같은 코드로 구성되어 있습니다. - 전달받은 타입을 생성할 수 있는 **init** - 각 기능을 구별할 수 있는 **id** - 실질적으로 기능이 구현되어있는 기능 Implement를 반환하는 **resolve** 메서드 ### Container ```swift public protocol ContainerAPI { func regist(injectType: Injectable.Type) func load(for injectID: String) -> Injectable? } public class Container: NSObject, ContainerAPI { private var injections: [String: Injectable] = [:] public static let shared: Container = Container() public func regist(injectType: Injectable.Type) { let injection = injectType.init() injections[injection.id] = injection } public func load(for injectID: String) -> Injectable? { injections[injectID] } } ``` Container의 코드는 위와 같이 구성되어 있습니다. 해당 모듈이 여러 모듈사이에서 쓰일 수 있고 각 모듈에서 주입받아야 하는 기능들을 한번에 관리해야하기 때문에 **싱글턴** 패턴을 이용하였습니다. - **injections** 프로퍼티를 통해 외부에 의존하는 기능들을 Dictionary로 관리합니다. 💡key로 Injectable 프로토콜에서 정의한 **id 프로퍼티를** 사용합니다. - **regist** 메서드를 이용하여 기능을 주입하는데, 파라미터에 Injectable 프로토콜을 conform하는 타입을 전달하고, 이를 init하여 injections 딕셔너리에 저장합니다. - injections 프로퍼티에 저장된 기능을 **load** 메서드를 통해 불러옵니다. # 사용 예시 1. 의존성을 주입할 기능에 대한 inject Protocol과 해당 기능을 유니크하게 식별할 수 있는 ID 값을 생성합니다. **(DependencyContainer 패키지)** ```swift // FileName : ToastInject public let toastInjectID = "ToastInjectID" public protocol ToastInject { func request(message: String, timeInterval: TimeInterval) } ``` 2. 해당 기능이 구현되어있는 프로젝트**(AfreecaTV 프로젝트)**에서 위 프로토콜을 conform 하는 타입을 생성한 뒤 메소드 내부를 구현해줍니다. ```swift // FileName : ToastImplement final class ToastImplement: ToastInject { public func request(message: String, timeInterval: TimeInterval) { AFToastView.showToast(delay: timeInterval, message: message) } } ``` 3. Container에 기능을 주입할 수 있도록 Injectable 프로토콜을 준수하는 아이템을 생성합니다. **(AfreecaTV 프로젝트)** id 프로퍼티에 아까 생성한 기능의 ID를 저장하고, resolve 메서드에서 위에 생성한 inject 프로토콜을 구현한 타입을 반환합니다. ```swift // FileName : ToastImplement final class ToastInjectItem: Injectable { var id: String = toastInjectID required init() { } func resolve() -> AnyObject { ToastImplement() } } ``` 4. **주입된 기능을 사용하려는 모듈**에서 Container에 담긴 기능을 빼내어 호출할 수 있도록 코드를 구성합니다. 여기서 아까 Container에서 구현한 load와 각 item에 정의된 resolve를 호출합니다. 이를 사용하고자 하는 inject 프로토콜로 변환하여 반환합니다. ```swift protocol ToastService { func showToast(message: String, timeInterval: TimeInterval) } struct DefaultToastService: ToastService { let toastService: ToastInject func showToast(message: String, timeInterval: TimeInterval) { toastService.request(message: message, timeInterval: timeInterval) } } struct ToastBuilder { static func build() -> ToastService? { guard let inject = Container.shared.load(for: toastInjectID)?.resolve() as? ToastInject else { return nil } return DefaultToastService(toastService: inject) } } ``` > 현재 LivePlayer는 Clean Architecture 구조를 사용중이므로 위와같이 Service로 빼내어 사용합니다. ### 위 코드로 만들어진 주입된 기능을 사용하려면 사용하려는 모듈에서 ```swift protocol ToastService { func showToast(message: String, timeInterval: TimeInterval) } struct DefaultToastService: ToastService { let toastService: ToastInject func showToast(message: String, timeInterval: TimeInterval) { toastService.request(message: message, timeInterval: timeInterval) } } struct ToastBuilder { static func build() -> ToastService? { guard let inject = Container.shared.load(for: toastInjectID)?.resolve() as? ToastInject else { return nil } return DefaultToastService(toastService: inject) } } // in Use ToastBuilder.build()?.showToast(message: "test", timeInterval: 3) ``` Container의 **load** 메서드를 이용하여 원하는 기능을 추출한 뒤, 이를 구조에 맞게 사용하면 됩니다.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully