IoC container for Dart inspired by Castle Windsor + Flutter MVVM framework

IoC container for Dart inspired by Castle Windsor + Flutter MVVM framework.

IoC and DI

Setup

IoC/DI package is platform independent so can be used in both command line apps and Flutter.

Just add it to your pubspec.yaml:

dependencies:
  factory_castle:

Creating container

import 'package:factory_castle/factory_castle.dart';

final container = FactoryContainer(); 

Component registration

As name suggests components are registered into container as factory deleagates. You have to manually inject dependencies into constructor (luckily, Dart will help you).

Reflection could be used to avoid manual injection but sadly dart:mirrors library is not available for Flutter. Reflection support for non-Flutter apps may be intorduced later via separate package.

Let’s register MyService which takes Logger and Config objects as parameters:

container.register<MyService>((c) => MyService(c.res<Logger>(), c.res<Config>()));

Dart is good at type inference so you don’t need to explicitly specify dependency types if they are the same as parameter types. You can also omit registered component type if you don’t want to abstract it with any interface.

Next example does exactly the same as previous one:

container.register((c) => MyService(c.res(), c.res()));

Each factory delegate recieves shorthand wrapper for current FactoryContainer instance as a parameter so that dependencies can be injected into constructor via res<>() method.

Components are resolved lazily which makes the order of registration not important. See the full example:

container.register((c) => MyService(c.res(), c.res()));
container.register((c) => Logger());
container.register((c) => Config(String.fromEnvironment('Flavor')));

Registering components under multiple interfaces is not supported yet. The following workaround is suggested:

final logger = FileLogger();
container.register<ILogger>((c) => logger);
container.register<Logger>((c) => logger);

Lifestyles

Names

Component overrides

Container hierarchy

Flutter state management and MVVM

Root widget

View

ViewModel

Service Locator

Obtaining TickerProvider

Example

Download Details:

Author: nuc134r

Source Code: https://github.com/nuc134r/factory_castle

#flutter #dart #mobile-apps

IoC container for Dart inspired by Castle Windsor + Flutter MVVM framework
10.45 GEEK