Factory injection in Angular-Dart DI library

本秂侑毒 提交于 2019-12-08 06:33:26

问题


In my Dart application I'm using the MVP pattern and the angular-dart Dependency Injection library(angular-di).

In the example above, I cannot inject MyView or MyPresenter, as this is a circular dependency.

class MyView {
    MyPresenter presenter;
    MyView(this.presenter);
}
class MyPresenter {
    MyView view;
    MyPresenter(this.view);
}

The way I usually did this in Java with Guice was injecting a Factory, like:

class MyView {
    MyPresenter presenter;
    MyView(this.presenter);
}
class MyPresenter {
    Factory<MyView> factoryView;
    MyView view;
    MyPresenter(this.factoryView) {
        view = factoryView(this);
    }
}

How do I accomplish this using angular-di? Is there possible to inject the factory without having to write the factory itself?


回答1:


Angular 2 Dart

typedef MyView MyViewFactoryFn(MyPresenter p);
provide(MyView, useValue: (MyPresenter p) => new MyView(p));

MyPresenter(MyViewFactoryFn vf) {
  view = vf(this);
}

or

typedef MyView MyViewFactoryFn(MyPresenter p);

MyView viewFactory(MyPresenter p) => new MyView(p)
const Provider(MyView, useFactory: viewFactory);

MyPresenter(MyViewFactoryFn vf) {
  view = vf(this);
}

See also

  • https://webdev.dartlang.org/angular/api/angular2.core/Provider-class
  • https://webdev.dartlang.org/angular/api/angular2.core/provide

Angular 1 Dart

You can bind a closure

typedef MyView MyViewFactoryFn(MyPresenter p);
bind(MyView, toValue: (MyPresenter p) => new MyView(p));

the constructor should then look like

MyPresenter(MyViewFactoryFn vf) {
  view = vf(this);
}

There is also a toFactory: but I guess DI will call the factory itself but I guess toValue: with a closure could work (not tried though).



来源:https://stackoverflow.com/questions/26389693/factory-injection-in-angular-dart-di-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!