1

I was reading a book about Learning ASP.NET Core API when I run to a part saying:

We create a private read-only field _repository that will be assigned the injected MockCommandAPIRepo object in our constructor and used throughout the rest of our code.

Here is some text I thought you'd better have: enter image description here

Then there are some explanations related to the picture above:

  1. Add the new using statement to reference ICommandAPIRepo.
  2. We create a private read-only field _repository that will be assigned the injected MockCommandAPIRepo object in our constructor and used throughout the rest of our code.
  3. The Class constructor will be called when we want to make use of our Controller.
  4. At the point when the constructor is called, the DI system will spring into action and inject the required dependency when we ask for an instance of ICommandAPIRepo. This is Constructor Dependency Injection.
  5. We assign the injected dependency (in this case MockCommandAPIRepo) to our private field (see point 1).

And that’s pretty much it! We can then use _repository to make use of our concrete implementation class, in this case MockCommandAPIRepo. As I’ve stated earlier, we’ll reuse this pattern multiple times through the rest of the tutorial; you’ll also see it everywhere in code in other projects – take note.

Now, According to the highlighted part above in number 2, I got a little confused! I've heard of "to be assigned by some value" before, but here, it is saying that:

that will be assigned the injected MockCommandAPIRepo object in our constructor

and as you see, there is no "by" added before the injected MockCommandAPIRepo object.... So, I have a question now. What does it mean by the highlighted part above in number 2? Does it mean the same when we add "by" in the sentence? or not?

Hossein
  • 142
  • 10

1 Answers1

1

This is about dependency injection in Asp.Net Core. After we register service to the IOC Container, How to use it in our controller? We can inject them in controller via Constructor Injection. Once we register a service, the IoC container automatically performs constructor injection if a service type is included as a parameter in a constructor. In your question, An IoC container will automatically pass an instance of ICommandAPIRepo(MockCommandAPIRepo) to the constructor of CommandsController. Now we can use MockCommandAPIRepo in the constructor. But it can only be used in constructor, How can we use it in other method in CommandsController? Here we use:

private readonly ICommandAPIRepo _repository;

to create a global variable in CommandsController, Then in constructor, We use:

_repository = repository 

assign the value of repository to _repository. Now _repository and repository has the same value, Because _repository is a global variable, So We can use _repository in other method in CommandsController. The whole process of dependency injection is done.

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12