Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't get service instance from $injector.get()

I define a customer service named "greeting", but can't get the instance from $injector.get('greeting'). It will throw such error: Unknown provider: greetingProvider <- greeting. So which is the right way to get it? Following is the code:

var app = angular.module('myDI', []);
app.config(function($provide){
    $provide.provider('greeting', function(){
        this.$get = function(){
             return function(name) {
                 console.log("Hello, " + name);
            };
        };
    });
});

var injector = angular.injector();
var greeting = injector.get('greeting');
greeting('Ford Prefect');
like image 878
jason Avatar asked Jul 27 '13 12:07

jason


People also ask

How does simple injector handle dependencies in servicecollection?

In case the dependency exists in IServiceCollection, Simple Injector ensures that the dependency is resolved from the .NET Core configuration system anytime it is requested—in other words, by requesting it from the IServiceProvider. In doing so, Simple Injector preserves the framework dependency’s lifestyle.

Can I use simple injector instead of the built-in container?

NOTE: Please note that when integrating Simple Injector, you do not replace .NET’s built-in container, as advised by the Microsoft documentation. The practice with Simple Injector is to use Simple Injector to build up object graphs of your application components and let the built-in container build framework and third-party components.

Can I use simple injector as an application developer?

As application developer, however, you wish to use Simple Injector to compose your application components. But those application components need to be fed with those framework and third-party services from time to time, which means framework components need to be pulled in from the .NET configuration system.

When is the simple injector container disposed of?

Fortunately, the AddSimpleInjector extension method ensures the Simple Injector Container is disposed of when the framework’s root IServiceProvider is disposed of. In an ASP.NET Core application, this typically means on application shutdown.


1 Answers

You need to create the injector from the module.

var app = angular.module('myDI', []);
app.config(function($provide){
    $provide.provider('greeting', function(){
        this.$get = function(){
             return function(name) {
                 console.log("Hello, " + name);
            };
        };
    });
});
var injector = angular.injector(['myDI', 'ng']); //Add this line
var greeting = injector.get('greeting');
greeting('Ford Prefect');
var injector = angular.injector();

Try it here. FIDDLE

like image 98
zs2020 Avatar answered Oct 15 '22 09:10

zs2020