User-893317190 posted
Hi ddesaraju ,
Dependency injection relates to how an object is created and set to another object's property or constructor.
For example,
public class A{
public string Apro1 {get;set;}
public B Bprop {get;set;}
}
public class B {
public string name{get;set;}
}
Here classA has a property of type B, which means classA depends on classB.
When injection container createA , if it finds it depends on classB, it will also create class B and set classA's Bprop property to the newly created class B.
Of cause, injection framework has many some ways to connect to the class you want to register into its container.
First, you should register a class to the injection container. Container is what injection framework use to maintain all the object you have registered.
Use an easy injection dependency framework unity as an example.
If I have interface IA IB.
public interface IA{}
public interface IB{}
Then I have two class A which implements IA , B which implements IB.
public class A:IA
{
[Dependency]
public IB B {get;set;}
}
public class B:IB
{
}
Unity use configuration file to register class. To be simple, I omit namespace.
<containers>
<container name="default">
<register type="IA" mapTo="A" >
<register type="IB" mapTo="B">
</container >
</containers>
In runtime, Unity will read this configuration file and know when an object is of tye IA , it should initialize class A.
When an object is of type IB , it should initialize classB.
Please pay attention to the attribute [Dependency] in classA.
Then classA and classB all registered into unity and unity could initialize them according to requirement.
It tells unity to inject an object of type IB in its container to classA's B property. Because classB is registered in the container, then the container gets it and inject into classA's B property.
Angular's injection system is similar.
When you write a service.
@Injectable({
providedIn: 'root',
})
export class HeroService {
constructor() { }
}
It will be registered in root injector of angular, because it is provided in root.
And then you could directly use it in your component , just need to define it in the constructor of the compoent.You don't need to worry about the initialize of heroService.
export class HeroListComponent {
heroes: Hero[];
constructor(heroService: HeroService) {
this.heroes = heroService.getHeroes();
}
}
However as you see HeroService is class name which is different from c# (usually c# is interface).
For more information about angular's injection system,please refer to
https://angular.io/guide/dependency-injection-in-action for complete guide.
Best regards,
Ackerly Xu