Code Monkey home page Code Monkey logo

swinject-codegen's Introduction

Swinject

Github Actions Carthage compatible CocoaPods Version License Platforms Swift Version Reviewed by Hound

Swinject is a lightweight dependency injection framework for Swift.

Dependency injection (DI) is a software design pattern that implements Inversion of Control (IoC) for resolving dependencies. In the pattern, Swinject helps your app split into loosely-coupled components, which can be developed, tested and maintained more easily. Swinject is powered by the Swift generic type system and first class functions to define dependencies of your app simply and fluently.

Swinject is maintained by the Faire Wholesale Inc. mobile platform team.

Features

Extensions

Requirements

  • iOS 11.0+ / Mac OS X 10.13+ / watchOS 4.0+ / tvOS 11.0+
  • Xcode 14.3+
  • Swift 4.2+
  • Carthage 0.18+ (if you use)
  • CocoaPods 1.1.1+ (if you use)

Installation

Swinject is available through Carthage, CocoaPods, or Swift Package Manager.

Carthage

To install Swinject with Carthage, add the following line to your Cartfile.

github "Swinject/Swinject"

# Uncomment if you use SwinjectStoryboard
# github "Swinject/SwinjectStoryboard"

Then run carthage update --no-use-binaries command or just carthage update. For details of the installation and usage of Carthage, visit its project page.

CocoaPods

To install Swinject with CocoaPods, add the following lines to your Podfile.

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '11.0' # or platform :osx, '10.13' if your target is OS X.
use_frameworks!

pod 'Swinject'

# Uncomment if you use SwinjectStoryboard
# pod 'SwinjectStoryboard'

Then run pod install command. For details of the installation and usage of CocoaPods, visit its official website.

Swift Package Manager

in Package.swift add the following:

dependencies: [
    // Dependencies declare other packages that this package depends on.
    // .package(url: /* package url */, from: "1.0.0"),
    .package(url: "https://github.com/Swinject/Swinject.git", from: "2.8.0")
],
targets: [
    .target(
        name: "MyProject",
        dependencies: [..., "Swinject"]
    )
    ...
]

Documentation

Basic Usage

First, register a service and component pair to a Container, where the component is created by the registered closure as a factory. In this example, Cat and PetOwner are component classes implementing Animal and Person service protocols, respectively.

let container = Container()
container.register(Animal.self) { _ in Cat(name: "Mimi") }
container.register(Person.self) { r in
    PetOwner(pet: r.resolve(Animal.self)!)
}

Then get an instance of a service from the container. The person is resolved to a pet owner, and playing with the cat named Mimi!

let person = container.resolve(Person.self)!
person.play() // prints "I'm playing with Mimi."

Where definitions of the protocols and classes are

protocol Animal {
    var name: String? { get }
}

class Cat: Animal {
    let name: String?

    init(name: String?) {
        self.name = name
    }
}

and

protocol Person {
    func play()
}

class PetOwner: Person {
    let pet: Animal

    init(pet: Animal) {
        self.pet = pet
    }

    func play() {
        let name = pet.name ?? "someone"
        print("I'm playing with \(name).")
    }
}

Notice that the pet of PetOwner is automatically set as the instance of Cat when Person is resolved to the instance of PetOwner. If a container already set up is given, you do not have to care what are the actual types of the services and how they are created with their dependency.

Where to Register Services

Services must be registered to a container before they are used. The typical registration approach will differ depending upon whether you are using SwinjectStoryboard or not.

The following view controller class is used in addition to the protocols and classes above in the examples below.

class PersonViewController: UIViewController {
    var person: Person?
}

With SwinjectStoryboard

Import SwinjectStoryboard at the top of your swift source file.

import SwinjectStoryboard

Services should be registered in an extension of SwinjectStoryboard if you use SwinjectStoryboard. Refer to the project page of SwinjectStoryboard for further details.

extension SwinjectStoryboard {
    @objc class func setup() {
        defaultContainer.register(Animal.self) { _ in Cat(name: "Mimi") }
        defaultContainer.register(Person.self) { r in
            PetOwner(pet: r.resolve(Animal.self)!)
        }
        defaultContainer.register(PersonViewController.self) { r in
            let controller = PersonViewController()
            controller.person = r.resolve(Person.self)
            return controller
        }
    }
}

Without SwinjectStoryboard

If you do not use SwinjectStoryboard to instantiate view controllers, services should be registered to a container in your application's AppDelegate. Registering before exiting application:didFinishLaunchingWithOptions: will ensure that the services are setup appropriately before they are used.

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    let container: Container = {
        let container = Container()
        container.register(Animal.self) { _ in Cat(name: "Mimi") }
        container.register(Person.self) { r in
            PetOwner(pet: r.resolve(Animal.self)!)
        }
        container.register(PersonViewController.self) { r in
            let controller = PersonViewController()
            controller.person = r.resolve(Person.self)
            return controller
        }
        return container
    }()

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

        // Instantiate a window.
        let window = UIWindow(frame: UIScreen.main.bounds)
        window.makeKeyAndVisible()
        self.window = window

        // Instantiate the root view controller with dependencies injected by the container.
        window.rootViewController = container.resolve(PersonViewController.self)

        return true
    }
}

Notice that the example uses a convenience initializer taking a closure to register services to the new instance of Container.

Play in Playground!

The project contains Sample-iOS.playground to demonstrate the features of Swinject. Download or clone the project, run the playground, modify it, and play with it to learn Swinject.

To run the playground in the project, first build the project, then select Editor > Execute Playground menu in Xcode.

Example Apps

Some example apps using Swinject can be found on GitHub.

Blog Posts

The following blog posts introduce the concept of dependency injection and Swinject.

Thanks the authors!

Contribution Guide

A guide to submit issues, to ask general questions, or to open pull requests is here.

Question?

Credits

The DI container features of Swinject are inspired by:

and highly inspired by:

License

MIT license. See the LICENSE file for details.

swinject-codegen's People

Contributors

ddengler avatar lutzifer avatar yoichitgy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

swinject-codegen's Issues

Use Pull Requests to Test Automatically before Merging into master

We've added tests to this project. Thanks @Lutzifer!

Now it's a very good practice to use Pull Requests to merge commits into master because the tests automatically run on Travis. You can keep master safe if you merge the Pull Requests after confirming the test results shown in the PRs.

It's ok to push a commit directly to master if it is a minor document update, but basically let's use PRs!

@Lutzifer plz close this issue if you got itπŸ˜€

ADD_DEPENDENCY syntax

@Lutzifer I would suggest to replace this with a simple comment block allowing any text to be placed as code in the resulting header instead of explicitly defining dependencies. This would be a lot more flexible. What do you think?

Release v0.5.0

Let's release CodeGen after we resolve all issues/tickets.

How to distribute the scripts?

We can use CocoaPods as Apple platform dependency management, Homebrew as Mac's package manager, or RubyGems because the scripts are written in Ruby.

Which one is good for our case?

How to test this?

we should add test cases to this, what would be a good way of specifying them in this case?

Rename executable file and project?

"CodeGen" is a well-known short name for "code generation". It looks good to rename our executable file and project to:

  • Executable: swinject_codegen
  • Project: Swinject-CodeGen

@Lutzifer: what do you think about the rename?

Is there any way how to use Swinject's Object Scopes with CodeGen?

Hello,

is there currently any way how to use Swinject's Object Scopes with CodeGen? Most importantly with the Container (aka Singleton) scope?

I have AuthenticationModel class which I put into dependencies.csv and Swinject CodeGen correctly generated registerAuthenticationModel() for me.

So I registered it and appended .inObjectScope(.Container) call as per documentation at https://github.com/Swinject/Swinject/blob/master/Documentation/ObjectScopes.md

container.registerAuthenticationModel { (resolver) -> (AuthenticationModel) in
            AuthenticationModel()
}.inObjectScope(.Container)

But when I later resolve the model by:

container.resolveAuthenticationModel()

I get always new instance of AuthenticationModel - what am I doing wrong here?

Or does the .inObjectScope(.Container) need to be directly after register() call? Like inside the generated registerAuthenticationModel()?

So this:

func registerAuthenticationModel(registerClosure: (resolver: ResolverType) -> (AuthenticationModel)) -> ServiceEntry<AuthenticationModel> {
        return self.register(AuthenticationModel.self, factory: registerClosure)
    }

would be:

func registerAuthenticationModel(registerClosure: (resolver: ResolverType) -> (AuthenticationModel)) -> ServiceEntry<AuthenticationModel> {
        return self.register(AuthenticationModel.self, factory: registerClosure).inObjectScope(.Container)
    }

It there any way to persuade CodeGen to put it there? Or do I miss something here?

Thanks for advice!

Have a nice day
Tom

GitFlow

Can we use a gitflow workflow with master/dev/feature?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.