Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ASP.NET 5 inject startup's dependencies?

I'm studying ASP.NET 5 documentation (It's great and better than the old one.) I understand that ASP.NET 5 includes a simple built-in inversion of control (IoC) container that supports constructor injection by default. As far as I know, configuring services and dependencies are done inside ConfigureServices() method.

The ConfigureServices() method is called after StartUp method.

So my question is: how does ASP.NET 5 internally inject Startup's dependencies?

I'd like to know that because if I want to inject another dependency, for example IFooEnviroment how can I do that?

like image 251
Sirwan Afifi Avatar asked Aug 18 '15 19:08

Sirwan Afifi


People also ask

How does ASP NET dependency injection work?

ASP.NET Core - Dependency Injection. ASP.NET Core is designed from scratch to support Dependency Injection. ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container.

Does ASP NET support dependency injection?

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.

How are dependencies injected into an object?

The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method. Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.

How is dependency injection done in C#?

Dependency Injection is done by supplying the DEPENDENCY through the class's constructor when creating the instance of that class. The injected component can be used anywhere within the class. Recommended to use when the injected dependency, you are using across the class methods.


1 Answers

The logic for this lives in the Hosting layer of ASP.NET 5:

  • the Startup type is determined
  • the hosting layer registers the required runtime services in the IServiceCollection
  • An internal service provider is build
  • an instance of the Startup class is created

You can of course register your own services in ConfigureServices. But they won't be available in the constructor as you already figured. There is no way to add your own services to the runtime services. This makes sense because there should be a difference between runtime services and application services.

You can however inject services registered in the ConfigureServices() method in the Configure() method.

like image 189
Henk Mollema Avatar answered Oct 19 '22 20:10

Henk Mollema