AngularJS中的IOC(1.x) - 我如何实现?

时间:2016-01-21 12:20:54

标签: javascript angularjs typescript inversion-of-control

我正在寻找将IOC添加到angularjs应用程序的方法。

我的应用是一个多租户应用,我需要为具有相同注册名称的不同租户使用不同的服务。

我也在使用TypeScript,它适用于在接口上使用具体类型。

我的主要问题是如何决定如何向我的应用程序注册正确的服务。

这是一个例子:

var app = angular.module('app',[]);

// common registrations
app.service('commonService1', commonServiceFunction1);
app.service('commonService2', commonServiceFunction2);
app.service('commonService3', commonServiceFunction3);
app.service('commonService4', commonServiceFunction4);

// here I want to register the same service name with a different implementation
app.service('serviceName', serviceOneFunction); // sometimes I will need this service
app.service('serviceName', serviceTwoFunction); // sometimes I will need this service

我想到的事情:

  1. 添加一些逻辑并为每个源下载正确的js文件 - 函数名称将保持不变,我需要找到一种方法来提供包含正确函数的正确js文件。

    < / LI>
  2. 覆盖注册(例如注册公共服务,然后使用特定实现覆盖注册)。

  3. 这两种解决方案都很丑陋而且不具备可扩展性。

    我希望有一个IOC容器或其他一些更好且可扩展的解决方案。

2 个答案:

答案 0 :(得分:1)

如果我理解了问题是正确的,您可以将服务(实际上是提供者)注册为您在角配置步骤配置的提供者。 所以,它可能看起来像这样:

var app = angular.module('app',[]);

// common registrations
app.service('commonService1', commonServiceFunction1);
app.service('commonService2', commonServiceFunction2);
app.service('commonService3', commonServiceFunction3);
app.service('commonService4', commonServiceFunction4);

app.provider('serviceName', function ServiceNameProvider() {
    var service = DefaultService;

    this.setService = function(newService) {
        service = newService
    }

    this.$get = [function() {
        return service;
    }];
});

app.config(["serviceNameProvider", function(serviceNameProvider) {  
    if(someCondition) {
        serviceNameProvider.setService(ServiceImpl1);
    } else {
        serviceNameProvider.setService(ServiceImpl2);
    } 
}]);

服务,工厂只是提供者的语法糖。您可以在角度配置阶段确定服务功能。 ServiceImpl1ServiceImpl2只是函数,但您可以在那里使用依赖项注入,因为它们将由提供程序with $injector.invoke调用。 Read about providers

答案 1 :(得分:0)

希望这会对你有所帮助。尝试使用角度工厂。

angular.module('app').factory('tenantService', function() {
  var tenantService = undefined;

  if(tenantType == "1"){
     tenantService = new TenantService1();
  } else if(tenantType == "2"){
     tenantService = new TenantService2();
  } else {
     tenantService = new TenantDefService();
  }
  return tenantService;
});