0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftライブラリLightWeightDIを使ったDIの実現

Last updated at Posted at 2024-05-26

SwiftによるDIの実現

  • 依存性の解決の方法はコンストラクタインジェクション、フィールドインジェクションなどがあります。ここではDIコンテナとSwiftの@PropertyWrapperを使ったライブラリLightWeightDIにより依存性を解決する方法を紹介します。

DIの必要性

サンプルはkotlinですが、言語仕様的に似てるので参考になります。
依存性注入について

LightWeightDIについて

LightWeightDIについて

  • 投稿者(anibe)が開発したお手軽にDIを実現するライブラリです。
  • Swift Package Manager Cocoapodsに対応してます。
  • 以下のようにあらかじめコンテナに登録してから使う。内部的に使ってるSwinjectと使い方は同じ
  • スコープを指定して登録します。
//プロトコルの型とimplのインスタンスの紐付け
        DependencyResolver.shared.regist(AppScopeProtocol.self, scope: .container) { r in
            return AppScopeProtocolImpl()
        }

        //injected AppScopeProtocol implementation object
        @Autowired var appObj: AppScopeProtocol

//プロトコルの型とimplのインスタンスの紐付け(default 弱参照)
        DependencyResolver.shared.regist(ARepository.self) { r in
            return ARepositoryImpl()
        }


  • DIして使う場合の記述方法、プロトコルやクラスを指定
  • @Autowired を使って指定の型をDIして使用する
@Autowired var repository: ARepository
@Autowired var appObj: AppScopeProtocol

細かい使用方法について

LightWeightDIを公開してみて、今後

  • SwiftでDIのライブラリ以外に少なくて、メジャーじゃないので、使いやすいように自分でこういうのあったらなあというのを作れた。
  • 仕事でCocoapods Swift package managerを使ったライブラリを作ったことがあったがその時の知見を整理できてよかった。
  • コンテナ部分をSwinjectを間借りしてるのでコンテナを時間ある時実装したい。それ終わったら1.0.0で公開する予定。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?