Giter Site home page Giter Site logo

nextbss / injector_io Goto Github PK

View Code? Open in Web Editor NEW
72.0 4.0 3.0 93 KB

InjectorIO - Dependency Injection for Flutter

License: MIT License

Kotlin 2.67% Swift 3.15% Objective-C 0.29% Dart 93.89%
flutter injection-framework injector flutter-package ango-dev-fest-2020 hacktoberfest

injector_io's Introduction

InjectorIO - Dependency Injection for Flutter

Pub support

Inject your dependencies easily and quickly. Register in one place and use get() everywhere to retrieve your instances and InjectorIO will take care of the rest.

Features

  • Create singleton instances;
  • Create factory instances (recreated on every call);
  • Register instances using Module;
  • Get instances from anywhere using the get() function.
  • Logs printed while in DEBUG mode.
  • Easy to test.
  • Doesn't use reflection.
  • InjectorIO prevents you from keeping instances of classes that extends Widget.

Core concepts

  • get() => Used to resolve the instance of a registered class. This is what you will use most.
  • inject() => Used to resolve a dependency inside a Module.
  • single() => Used to register a singleton instance. You will receive a the same instance every time you use get().
  • factory() => Used to register a factory instance. You will receive a new instance every time you use get().

NOTE: don't get confused with get() and inject(). Just remember this: If you are inside a Module and you want to resolve a dependency use inject(), but if you are not within a Module always use get().

Usage

Basic Sample

Here is how you can easily use this package. Import this package and register your dependency instance, then in any part of your code use get() to resolve the registered instance.

import 'package:injectorio/injectorio.dart';

void main(){
  InjectorIO.start()
  .single( CountriesRepository()); // register a instance

  runApp(MyApp());
}

class _MyHomePageState extends State<MyHomePage> {
  // This works
  // final CountriesRepository repository = get();

  CountriesRepository _repository;

  @override
  void initState() {
    super.initState();
    _repository = get(); // resolve the dependency
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Register Dependencies

import 'package:injectorio/injectorio.dart';

void main() {
  InjectorIO.start()
  .single(CountriesWebService())
  .factory(() => CountriesRepository(get()));

  runApp(MyApp());
}

Register Dependencies using Module

import 'package:injectorio/injectorio.dart';

class CountriesWebService{}

class CountriesRepository{
  final CountriesWebService webService;
  CountriesRepository(this.webService);
}

class AppModule extends Module{
  AppModule() {
    single( CountriesWebService()); // register a singleton of CountriesWebService
    factory(CountriesRepository(inject())); // the library will take care of getting the instance of CountriesWebService
  }
}

void main(){
  InjectorIO.start()
  .module(AppModule());

  runApp(MyApp());
}

Enable/Disable Logs

InjectorIO can also provide printed logs while in development mode. The function InjectorIO.start() receives a InjectorMode that can be:

  • DEBUG - Displays logs
  • PRODUCTION - Disables logs. You will not see logs from this package in the console.

The default value for this is DEBUG. If you don't want to see logs, just use production mode:

InjectorIO.start(mode: InjectorMode.PRODUCTION)
.module( AppModule());

Help this Library

You can help/support by:

  • Reporting a Bug;
  • Making pull request;
  • Write a tutorial about this;
  • ❤️ Staring this repository;

injector_io's People

Contributors

alexjuca avatar mohn93 avatar pedromassango 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  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  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

injector_io's Issues

Add support for interfaces

Is not possible to instantiate concrete classes from their base classes, this a severe limitation.

BaseClass base = get<BaseClass>(); // Instantiate ConcreteClass

The code below would probably be an API breaking change:

factory<CacheStore>(() => FileCacheStore(inject()))

Combine dependencies from multiple modules

Provide possibility to create instances with dependencies provided from other modules.

class RepositoriesModule extends Module {
  RepositoriesModule () {
    // PersonRepository depends of PersonWebService
    factory(DependentRequestsRepository(inject()), () =>
        DependentRequestsRepository(inject()));
  }
}

class WebServicesModules extends Module {
    WebServicesModules() {
        factory(PersonWebService(), () => PersonWebService());
    }
}

Example not working

I am running your test application, but it doesn't work.

flutter (31735): │ 🐛 Initiated InjectorIO in mode: InjectorMode.DEBUG
I/flutter (31735): └───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
I/flutter (31735): ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
I/flutter (31735): │ #0   DefinitionRegistry._log (package:injectorio/src/bean_registry.dart:83:44)
I/flutter (31735): │ #1   DefinitionRegistry._showInstanceNotFound (package:injectorio/src/bean_registry.dart:91:7)
I/flutter (31735): ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
I/flutter (31735): │ 🐛 InjectorIO:::	!!!--- Instance of type CountriesWebService not found ---!!!
I/flutter (31735): └───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
E/flutter (31735): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Exception: Instance of CountriesWebService not found. Make sure you added
E/flutter (31735):         it by using module or with [single()], [factory()] definition.
E/flutter (31735): #0      DefinitionRegistry.get (package:injectorio/src/bean_registry.dart:60:7)
E/flutter (31735): #1      get (package:injectorio/src/component_binder.dart:22:24)
E/flutter (31735): #2      get (package:injectorio/injectorio.dart:9:15)
E/flutter (31735): #3      new AppModule (package:example/main.dart:24:34)
E/flutter (31735): #4      main (package:example/main.dart:30:12)
E/flutter (31735): #5      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:140:25)
E/flutter (31735): #6      _rootRun (dart:async/zone.dart:1354:13)
E/flutter (31735): #7      _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (31735): #8      _runZoned (dart:async/zone.dart:1788:10)
E/flutter (31735): #9      runZonedGuarded (dart:async/zone.dart:1776:12)
E/flutter (31735): #10     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:133:5)
E/flutter (31735): #11     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (31735): #12     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter (31735): 
I/assango.exampl(31735): ProcessProfilingInfo new_methods=310 is saved saved_to_disk=1 resolve_classes_delay=8000
W/BpBinder(31735): Slow Binder: BpBinder transact took 302 ms, interface=android.ui.ISurfaceComposer, code=8 oneway=false
W/Looper  (31735): Slow Looper main: doFrame is 337ms late because of 2 msg, msg 1 took 336ms (seq=25 running=8ms runnable=19ms late=6ms h=android.app.ActivityThread$H w=137)

Bug when trying to declare nested dependencies

Hi.
I'm having trouble to do nested dependencies injection. I have a AppModule like this:


class Dependencies extends Module {
  Dependencies() {
    single(DioDart());
    single(JobsController(get()));  <===== here's the problem, the lib cant find DiotDart instance, but it has already declared above

    single(JobsService(get()));
    single(JobTypesServices());
    single(AuthServices());
    single(ServiceProvidersService(get()));
    single(UsersService());
  }
}

JobsController snippet:

  static String endpoint = '${apiURL}/jobs';
  DioDart dioDart;
  JobsController(this.dioDart);

Console error Stack (Debug mode):

[Easy Localization] Load asset from assets/i18n
I/flutter (21971): ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
I/flutter (21971): │ #0   new InjectorIO.start (package:injectorio/src/io.dart:44:14)
I/flutter (21971): │ #1   MyApp.build (package:bridi_mobile/main.dart:47:16)
I/flutter (21971): ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
I/flutter (21971): │ 🐛 Initiated InjectorIO in mode: InjectorMode.DEBUG
I/flutter (21971): └───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
I/flutter (21971): ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
I/flutter (21971): │ #0   DefinitionRegistry._log (package:injectorio/src/bean_registry.dart:83:44)
I/flutter (21971): │ #1   DefinitionRegistry._showInstanceNotFound (package:injectorio/src/bean_registry.dart:91:7)
I/flutter (21971): ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
I/flutter (21971): │ 🐛 InjectorIO:::	!!!--- Instance of type DioDart not found ---!!!
I/flutter (21971): └───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
[Easy Localization] Build
[Easy Localization] Init Localization Delegate
[Easy Localization] Init provider

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following _Exception was thrown building MyApp(dirty, dependencies: [_InheritedProviderScope<ThemeController>]):
Exception: Instance of DioDart not found. Make sure you added
        it by using module or with [single()], [factory()] definition.

The relevant error-causing widget was: 
  MyApp file:///home/ark/Haizen/projetox/bakcup/bridi-mobile/lib/main.dart:34:18
When the exception was thrown, this was the stack: 
#0      DefinitionRegistry.get (package:injectorio/src/bean_registry.dart:60:7)
#1      get (package:injectorio/src/component_binder.dart:22:24)
#2      get (package:injectorio/injectorio.dart:9:15)
#3      new Dependencies (package:bridi_mobile/main.dependencies.dart:14:27)
#4      MyApp.build (package:bridi_mobile/main.dart:47:31)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

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.