Skip to content

Dependency Injection

Steve Ives edited this page May 26, 2020 · 2 revisions

Harmony Core Logo

Dependency Injection

Basic Concepts

Dependency injection is a technique in which an object receives other objects that it depends on. These other objects are called dependencies. In the typical "using" relationship the receiving object is called a client and the passed (that is, "injected") object is called a service. The code that passes the service to the client can be many kinds of things and is called the injector. Instead of the client specifying which service it will use, the injector tells the client what service to use. The "injection" refers to the passing of a dependency (a service) into the object (a client) that would use it.

The service is made part of the client's state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

The intent behind dependency injection is to achieve separation of concerns of construction and use of objects. This can increase readability and code reuse.

Dependency injection is one form of the broader technique of inversion of control. A client who wants to call some services should not have to know how to construct those services. Instead, the client delegates the responsibility of providing its services to external code (the injector). The client is not allowed to call the injector code;[3] it is the injector that constructs the services. The injector then injects (passes) the services into the client which might already exist or may also be constructed by the injector. The client then uses the services. This means the client does not need to know about the injector, how to construct the services, or even which actual services it is using. The client only needs to know about the intrinsic interfaces of the services because these define how the client may use the services. This separates the responsibility of "use" from the responsibility of "construction".

For more information, see Wikipedia.

Specific Implementation

At its most basic level, dependency injection consists of three parts.

The first is an IServiceProvider. If you have an instance of IServiceProvider, you can ask it to provide you with an instance of a Type that has previously been registered.

The second part is the class that needs to be constructed. For example, if your constructor takes a String parameter, it will receive an instance of a String as registered in your IServiceProvider when an object is constructed.

The third part, the part that glues it all together, is ActivatorUtilities.CreateInstance<YourTypeGoesHere>(IServiceProvider). CreateInstance actually takes all the services provided by the passed-in provider and creates a new instance of the type you supplied using a type argument.

For more information, see Dependency injection in ASP.NET Core.

Clone this wiki locally