패키지, 저장소 및 앱 카테고리 검색

패키지 상세v2.0.0

flutter_simple_dependency_injection

Flutter용 매우 간단한 종속성 주입 구현으로, 일반적인 IOC 컨테이너처럼 동작하며 미러에 의존하지 않습니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
3.9천
좋아요
74
Pub 점수
160

패키지 설치

flutter pub add flutter_simple_dependency_injection

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Flutter용 가벼운 종속성 주입 패키지로, 간단하고 거울 없는 IOC 컨테이너를 제공합니다. 개발자가 앱 전반에서 의존성을 쉽게 등록하고 해결할 수 있게 해주어 관심사의 명확한 분리를 가능하게 합니다. 단순성과 성능을 고려해 설계되었으며, 런타임 반사 기능을 사용하지 않아 트리셰이킹 지원을 통해 프로덕션 앱에 적합합니다. API는 직관적이며 기존의 Flutter 프로젝트에 복잡함 없이 원활하게 통합됩니다.

사용 사례

  • 여러 위젯에 걸쳐 공유 서비스 관리하기
  • 리포지터리 및 데이터 소스 주입
  • 모의 종속성으로 테스트
  • 복잡한 객체 그래프 초기화 간소화
  • 모듈식 앱 아키텍처 활성화

주요 기능

  • 미러 없는 종속성 해결
  • 간단한 등록 및 검색 구문
  • 싱글턴 및 일시적 인스턴스 지원
  • 모든 플러터 플랫폼에서 작동합니다
  • 경량이며 빠른 시작

적합한 대상

  • 작은에서 중간 규모의 Flutter 애플리케이션
  • DI를 위한 최소 설정을 원하는 팀
  • 성능과 트리 쉐이킹을 우선 고려하는 프로젝트
  • 복잡한 DI 프레임워크를 피하는 개발자

고려 사항

  • 완전한 DI 컨테이너와 비교하여 고급 기능이 제한됨
  • 계층적 범위에 대한 내장 지원 없음
  • 복잡한 시나리오에서 라이프사이클 수동 관리
  • 복잡한 종속성 트리가 있는 대규모 기업용 앱에는 적합하지 않음

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

flutter_simple_dependency_injection

A simple dependency injection plugin for Flutter and Dart.

This implementation does not rely on the dart reflection apis (mirrors) and favours a simple factory based approach. This increases the performance and simplicity of this implementation.

  • Support for multiple injectors (useful for unit testing or code running in isolates)
  • Support for types and named types
  • Support for singletons
  • Support simple values (useful for configuration parameters like api keys or urls)

Any help is appreciated! Comment, suggestions, issues, PR's!

Getting Started

In your flutter or dart project add the dependency:

dependencies:
  ...
  flutter_simple_dependency_injection: any

For help getting started with Flutter, view the online documentation.

Usage example

Import flutter_simple_dependency_injection

import 'package:flutter_simple_dependency_injection/injector.dart';
Injector Configuration

As this injector relies on factories rather than reflection (as mirrors in not available in Flutter) each mapped type needs to provide a factory function. In most cases this can just be a simple new object returned function. In slightly more advanced scenarios where the type to be created relies on other types an injector instances is passed into the factory function to allow the type of be created to get other types it depends on (see below for examples).

import 'package:flutter_simple_dependency_injection/injector.dart';

void main() {
  // it is best to place all injector initialisation work into one or more modules
  // so it can act more like a dependency injector than a service locator.
  // The Injector implements a singleton pattern. You can get a singleton injector instance
  // just by calling Injector().
  final injector = ModuleContainer().initialise(Injector());

  // NOTE: it is best to architect your code so that you never need to
  // interact with the injector itself.  Make this framework act like a dependency injector
  // by having dependencies injected into objects in their constructors.  That way you avoid
  // any tight coupling with the injector itself.

  // Basic usage, however this kind of tight couple and direct interaction with the injector
  // should be limited.  Instead prefer dependencies injection.

  // simple dependency retrieval and method call
  injector.get<SomeService>().doSomething();

  // get an instance of each of the same mapped types
  final instances = injector.getAll<SomeType>();
  print(instances.length); // prints '3'

  // passing in additional arguments when getting an instance
  final instance =
      injector.get<SomeOtherType>(additionalParameters: {"id": "some-id"});
  print(instance.id); // prints 'some-id'
}

class ModuleContainer {
  Injector initialise(Injector injector) {
    injector.map<Logger>((i) => Logger(), isSingleton: true);
    injector.map<String>((i) => "https://api.com/", key: "apiUrl");
    injector.map<SomeService>(
        (i) => SomeService(i.get<Logger>(), i.get<String>(key: "apiUrl")));

    // note that you can configure mapping in a fluent programming style too
    injector.map<SomeType>((injector) => SomeType("0"))
            ..map<SomeType>((injector) => SomeType("1"), key: "One")
            ..map<SomeType>((injector) => SomeType("2"), key: "Two");

    injector.mapWithParams<SomeOtherType>((i, p) => SomeOtherType(p["id"]));

    return injector;
  }
}

class Logger {
  void log(String message) => print(message);
}

class SomeService {
  final Logger _logger;
  final String _apiUrl;

  SomeService(this._logger, this._apiUrl);

  void doSomething() {
    _logger.log("Doing something with the api at '$_apiUrl'");
  }
}

class SomeType {
  final String id;
  SomeType(this.id);
}

class SomeOtherType {
  final String id;
  SomeOtherType(this.id);
}

Remove mappings

You can remove a mapped a factory/instance at any time:

  injector.removeMapping<SomeType>();

  injector.removeMapping<SomeType>(key: 'some_key');

  injector.removeAllMappings<SomeType>();
Multiple Injectors

The Injector class has a factory constructor that by default returns the default singleton instance of the injector. In most cases this will be enough. However, you can pass a name into this factory constructor to return another isolated injector that is independent from the default injector. Passing in a new injector name will create the injector if it has not be retrieved before.

  final defaultInjector = Injector();
  final isolatedInjector = Injector("Isolated");

To destroy an injector instance call its dispose method. The particular instance of the injector with all mappings will be removed.

  Injector().dispose();
  Injector("Isolated").dispose();

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트