“Factory” and “Service” are different ways of doing DI (Dependency injection) in angular
So when we define DI using “service” as shown in the code below. This creates a new GLOBAL instance of the “Logger” object and injects it in to the function.
app.service("Logger", Logger); // Injects a global object
When you define DI using a “factory” it does not create a instance.
It just passes the method and later the consumer internally has to make
calls to the factory for object instances.app.factory("Customerfactory", CreateCustomer);
Below is a simple image which shows visually how DI process for “Service” is different than “Factory”.Factory | Service | |
Usage | When we want to create different types of objects depending on scenarios. For example depending on scenario we want to create a simple “Customer” object , or “Customer” with “Address” object or “Customer” with “Phone” object. See the previous question for more detailed understanding. | When we have utility or shared functions to be injected like Utility , Logger , Error handler etc. |
Instance | No Instance created. A method pointer is passed. | Global and Shared instance is created. |
No comments:
Post a Comment