• Stars
    star
    971
  • Rank 45,274 (Top 1.0 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple Swift Dependency container. Use protocols to resolve your dependencies and avoid singletons / sharedInstances!

Dip

CI Status Version Carthage Compatible License Platform Swift Version Swift Version

Animated Dipping GIF
Photo courtesy of www.kevinandamanda.com

Introduction

Dip is a simple Dependency Injection Container.

It's aimed to be as simple as possible yet provide rich functionality usual for DI containers on other platforms. It's inspired by .NET's Unity Container and other DI containers.

  • You start by creating let container = DependencyContainer() and registering your dependencies, by associating a protocol or type to a factory using container.register { MyService() as Service }.
  • Then you can call container.resolve() as Service to resolve an instance of protocol or type using that DependencyContainer.
  • You can easily use Dip along with Storyboards and Nibs . There is also a code generator that can help to simplify registering new components.
Basic usage
import Dip

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    // Create the container
    private let container = DependencyContainer { container in
    
        // Register some factory. ServiceImp here implements protocol Service
        container.register { ServiceImp() as Service }
    }

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
        
        // Resolve a concrete instance. Container will instantiate new instance of ServiceImp
        let service = try! container.resolve() as Service
    
        ...
    }
}
More sophisticated example
import Dip

class AppDelegate: UIResponder, UIApplicationDelegate {
	private let container = DependencyContainer.configure()
	...
}

//CompositionRoot.swift
import Dip
import DipUI

extension DependencyContainer {

	static func configure() -> DependencyContainer {
		return DependencyContainer { container in 
			unowned let container = container
			DependencyContainer.uiContainers = [container]
		
			container.register(tag: "ViewController") { ViewController() }
			  .resolvingProperties { container, controller in
				  controller.animationsFactory = try container.resolve() as AnimatonsFactory
			}
    
			container.register { AuthFormBehaviourImp(apiClient: $0) as AuthFormBehaviour }
			container.register { container as AnimationsFactory }
			container.register { view in ShakeAnimationImp(view: view) as ShakeAnimation }
			container.register { APIClient(baseURL: NSURL(string: "http://localhost:2368")!) as ApiClient }
		}
	}

}

extension DependencyContainer: AnimationsFactory { 
    func shakeAnimation(view: UIView) -> ShakeAnimation {
        return try! self.resolve(withArguments: view)
    }
}

extension ViewController: StoryboardInstantiatable {}

//ViewController.swift

class ViewController {
    var animationsFactory: AnimationsFactory?

    private let _formBehaviour = Injected<AuthFormBehaviour>()
    
    var formBehaviour: AuthFormBehaviour? {
        return _formBehaviour.value
    }
	...
}

Documentation & Usage Examples

Dip is completely documented and comes with a Playground that lets you try all its features and become familiar with API. You can find it in Dip.xcworkspace.

Note: it may happen that you will need to build Dip framework before playground will be able to use it. For that select Dip scheme and build for iPhone Simulator.

You can find bunch of usage examples and usfull tips in a wiki.

If your are using VIPER architecture - here is VIPER demo app that uses Dip instead of manual dependency injection.

There are also several blog posts that describe how to use Dip and some of its implementation details:

File an issue if you have any question. Pull requests are warmly welcome too.

Features

  • Scopes. Dip supports 5 different scopes (or life cycle strategies): Unique, Shared, Singleton, EagerSingleton, WeakSingleton;
  • Auto-wiring & Auto-injection. Dip can infer your components' dependencies injected in constructor and automatically resolve them as well as dependencies injected with properties.
  • Resolving optionals. Dip is able to resolve constructor or property dependencies defined as optionals.
  • Type forwarding. You can register the same factory to resolve different types implemeted by a single class.
  • Circular dependencies. Dip will be able to resolve circular dependencies if you will follow some simple rules;
  • Storyboards integration. You can easily use Dip along with storyboards and Xibs without ever referencing container in your view controller's code;
  • Named definitions. You can register different factories for the same protocol or type by registering them with tags;
  • Runtime arguments. You can register factories that accept up to 6 runtime arguments (and extend it if you need);
  • Easy configuration & Code generation. No complex containers hierarchy, no unneeded functionality. Tired of writing all registrations by hand? There is a cool code generator that will create them for you. The only thing you need is to annotate your code with some comments.
  • Weakly typed components. Dip can resolve "weak" types when they are unknown at compile time.
  • Thread safety. Registering and resolving components is thread safe;
  • Helpful error messages and configuration validation. You can validate your container configuration. If something can not be resolved at runtime Dip throws an error that completely describes the issue;

Installation

You can install Dip using your favorite dependency manager:

CocoaPods

pod "Dip"

Carthage
github "AliSoftware/Dip"

To build for Swift 2.3 run Carthage with --toolchain com.apple.dt.toolchain.Swift_2_3 option.

Swift Package Manager
.Package(url: "https://github.com/AliSoftware/Dip", majorVersion: 5, minor: 0)

Running tests

On OSX you can run tests from Xcode. On Linux you need to have Swift Package Manager installed and use it to build and run tests using this command: swift build --clean && swift build && swift test

Credits

This library has been created by Olivier Halligon and is maintained by Ilya Puchka.

Dip is available under the MIT license. See the LICENSE file for more info.

The animated GIF at the top of this README.md is from this recipe on the yummy blog of Kevin & Amanda. Go try the recipe!

The image used as the SampleApp LaunchScreen and Icon is from Matthew Hine and is under CC-by-2.0.

More Repositories

1

OHHTTPStubs

Stub your network requests easily! Test your apps with fake network data and custom response time, response code and headers!
Objective-C
5,014
star
2

Reusable

A Swift mixin for reusing views easily and in a type-safe way (UITableViewCells, UICollectionViewCells, custom UIViews, ViewControllers, Storyboards…)
Swift
2,973
star
3

OHAttributedLabel

UILabel that supports NSAttributedString
Objective-C
1,511
star
4

UIImage-Resize

Category to add some resizing methods to the UIImage class, to resize it to a given CGSize β€” or fit in a CGSize keeping aspect ratio
Objective-C
354
star
5

OHAutoNIBi18n

Automate the Localization/Translation of your XIB & interface without any additional code nor IBOutlet!
Objective-C
120
star
6

OHAttributedStringAdditions

NSAttributedString Additions that add convenience methods to manipulate attributed strings easily
Objective-C
106
star
7

SourceryTemplates

Some templates to use for Code Generation in Swift with http://github.com/krzysztofzablocki/Sourcery
HTML
99
star
8

OHGridView

View that display cells as a grid. Uses quite the same API as UITableView
Objective-C
71
star
9

OHPDFImage

A library to easily load PDF files as UIImages
Objective-C
56
star
10

Dip-UI

UI Extensions for https://github.com/AliSoftware/Dip
Swift
48
star
11

OHSwipeWheel

A widget to choose between multiple values by swiping an horizontal wheel. This is kinda like a UIPickerView but rolling horizontally and that takes much less space
Objective-C
42
star
12

pprof

Ruby Gem to list, filter, search and print Provisioning Profiles files
Ruby
39
star
13

Xcode-Utils

A set of useful templates, macros, etc. to use with the Apple Developer Tools
Objective-C
32
star
14

OpeningHours

A small iOS app to keep the list of Opening Hours for your local shops you're used to go to
Swift
28
star
15

OHActionSheet

UIActionSheet subclass that uses blocks to handle its callback (which make the code much more easier and readable)
Objective-C
27
star
16

OHStackView

This class automatically stack its subviews and relayout them when one of them change its size.
Objective-C
25
star
17

OHAlertView-OHActionSheet

This repo is obsolete. Use OHAlertView and OHActionSheet repos now.
Objective-C
21
star
18

OHURLLoader

Class that uses blocks (new to iOS4/OSX 10.6) to make URL requests/downloads much more easier
Objective-C
19
star
19

OHAlertView

UIAlertView subclass that uses blocks to handle its callback (which make the code much more easier and readable)
Objective-C
16
star
20

AliJSONRPC

A JSON-RPC Framework for Cocoa. Supports JSON-RPC 1.0, 1.1 and 2.0
Objective-C
13
star
21

alisoftware.github.io

AliSoftware's Blog "Crunchy Development": making Swift Magic ✨
SCSS
12
star
22

SWPromisesDemo

A demo project implementing the StarWars API (swapi.co) in Swift with PromiseKit
Swift
8
star
23

generate-enum-allvalues

Automatically generate a `static let allValues` for your Swift enums
Swift
8
star
24

FunctionalVCDemo

Demo for the Functional ViewControllers concept in RxSwift
Swift
8
star
25

MagicSwiftNoStrings

Demo project demonstrate some nice patterns to get rid of String-based API using enums, mixins and SwiftGen
Swift
8
star
26

CodeGen-Workshop

This is the repository used for my SwiftAveiro'19 Workshop about Code Generation
Swift
6
star
27

FormWorkflow

A sample project to demonstrate how to use Promises to describe a workflow of Screens/ViewControllers
Swift
6
star
28

ObjcSwitch

A category to allow you to use the "switch/case"-like syntax with NSObjects (and not just integers/enums!)
Objective-C
6
star
29

KeyPathObserver

Execute blocks when a given property changes (this is KVO, the block-style way)
Objective-C
5
star
30

talks

My talks at conferences
5
star
31

CodeGenDemo

Demo project to show the advantages of Code Generation with SwiftGen & Sourcery
Swift
4
star
32

AliSoftware

3
star
33

SwiftDependencyInjectionTest

A test project to play around and explore some Dependency Injection ideas in Swift β€” This was the POC that led to Dip
Swift
3
star
34

banana-crumb-muffins

This is the recipe for Banana Crumb Muffins, presented as a GitHub repository (one commit for each step of the recipe). Just for fun.
2
star
35

TVShowOrganizer

Ruby
2
star
36

XCAssetsSample

This sample project try to expose a complex case of using multiple assets with multiple targets. Originally created to test CocoaPods/CocoaPods#3263
Objective-C
2
star
37

xcodeplugin

Tools to generate dvtplugin / xcodeplugins especially for PLIST-files structure definitions
Shell
2
star