0% found this document useful (0 votes)
51 views8 pages

Dependency Injection

This document provides a summary of dependency injection in ASP.NET. It explains that dependency injection involves creating service objects outside of client objects and injecting them through constructors. It describes how the IoC container manages the lifecycle of services registered with AddTransient, AddScoped, or AddSingleton. Services are registered in Startup.ConfigureServices and referenced by interfaces to follow dependency inversion. The AddDbContext method is used to register database contexts.

Uploaded by

cf8qrn9q4r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views8 pages

Dependency Injection

This document provides a summary of dependency injection in ASP.NET. It explains that dependency injection involves creating service objects outside of client objects and injecting them through constructors. It describes how the IoC container manages the lifecycle of services registered with AddTransient, AddScoped, or AddSingleton. Services are registered in Startup.ConfigureServices and referenced by interfaces to follow dependency inversion. The AddDbContext method is used to register database contexts.

Uploaded by

cf8qrn9q4r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

19/01/2024, 13:10 Learn ASP.NET: ASP.

NET: Dependency Injection Cheatsheet | Codecademy


Cheatsheets / Learn ASP.NET

ASP.NET: Dependency Injection

https://www.codecademy.com/learn/learn-asp-net/modules/asp-net-dependency-injection/cheatsheet 1/8
19/01/2024, 13:10 Learn ASP.NET: ASP.NET: Dependency Injection Cheatsheet | Codecademy

Dependency Injection

When a service (dependency object) is created outside //The client class that depends on a
of its client (the object that depends on it) that service
service
can be passed into, or injected, into the client, typically
through the client’s constructor. class Reviewer
This process is called dependency injection, where {
services are not created by the clients that use (and
public EmailSender _sender {get; set;}
depend on) them, but rather are created and managed
in other code, and are injected into the client.
//EmailSender is injected into the
Reviewer object
public Reviewer(EmailSender sender)
{
_sender = sender;
}
public SendReview(string lesson, string
comments)
{
_sender.SendReview(lesson, comments);
}
}

//The dependency/service class


class EmailSender
{
public SendReview(string lesson, string
comments)
{
// Send an email with the Lesson and
Comments
}
}

static void Main(string[] args)


{
EmailSender sender = new EmailSender();

//Injecting Sender into Reviewer


Reviewer reviewer = new
Reviewer(Sender).
SendReview("Dependecy Injection",
"Super helpful!");

https://www.codecademy.com/learn/learn-asp-net/modules/asp-net-dependency-injection/cheatsheet 2/8
19/01/2024, 13:10 Learn ASP.NET: ASP.NET: Dependency Injection Cheatsheet | Codecademy
}

IoC Container

The IoC Container (Inversion of Control Container) is a


framework that acts as the dependency injector. This
allows the programmer to focus on using the service
within the classes that depend on it, rather than
managing the entire life cycle of the service.
The IoC Container does all of the following:
1. Registers services with a concrete
implementation (a class)
2. Instantiating, or resolving, the service class to
be injected into the client class
3. Injecting the service
4. Disposing of the service instance based on the
registered settings

Registering Services

Services are registered in the public void


ConfigureServices() method of the
ConfigureServices(IServiceCollection
Startup class in Startup.cs.
Once the services are registered, they are available for services)
injection into client classes that use those services. {
Services are registered using the
services.AddRazorPages();
AddTransient() , AddScoped() , and
AddSingleton() methods. These methods
dictate how the service’s life cycle is managed.
AddTransient - the service is created services.AddTransient<ITransientService,
each time it’s requested from the IoC
TransientService>();
Container. This means that when more than one
class uses the service, those classes will be services.AddScoped<IScopedService,
injected with a fresh new instance of that ScopedService>();
service, even if it’s within the same request.
AddScoped - the service is created for
each client request. If multiple classes use and
services.AddSingleton<ISingletonService,
are injected with the service within the same SingletonService>();
request, only one instance of that service is }
created and used throughout the request for
those classes.
AddSingleton - the service is created
once on the first time the service is requested
and is instantiated for the lifetime of the
application process.

https://www.codecademy.com/learn/learn-asp-net/modules/asp-net-dependency-injection/cheatsheet 3/8
19/01/2024, 13:10 Learn ASP.NET: ASP.NET: Dependency Injection Cheatsheet | Codecademy

AddDbContext

The AddDbContext<T>() method registers the public void


framework-provided services that allow all page models
ConfigureServices(IServiceCollection
to be injected with an instance of the T database
context that will be used to access the application’s services)
database. {
When calling the AddDbContext<T>() method services.AddDbContext<MyAppContext>
to register the application’s database context service,
(options =>
one must also pass in an instance of the
DbContextOptions object that contains options.UseSqlServer(
information such as the database provider type
( UseSqlServer() , UseSqlite() , etc.),
Configuration.GetConnectionString("MyAppC
connection string (defined in appsettings.json), and
other optional settings that defines the behavior of the ontext")));
context. }
The AddDbContext<T>() method is called
within Startup.ConfigureServices() .

https://www.codecademy.com/learn/learn-asp-net/modules/asp-net-dependency-injection/cheatsheet 4/8
19/01/2024, 13:10 Learn ASP.NET: ASP.NET: Dependency Injection Cheatsheet | Codecademy

Dependencies As Interfaces

In order to satisfy the Dependency Inversion Principle, public class ReviewModel : PageModel
injected services are typically referenced as interfaces.
{
This allows the client class to use an implemented
service whose behavior is well defined via its interface, // Notice IFormSender interface
and not have any knowledge or be concerned with the private readonly IFormSender _Sender;
actual concrete class that implements that interface.
Any changes to the concrete class’s methods or
properties would not require any modifications to the [BindProperty]
client class since it only knows of the interface and its public string Review {get;set;}
well defined abstract methods.

[BindProperty]
public int ProductID {get;set}

// Notice IFormSender interface


public ReviewModel(IFormSender sender)
{
_Sender = sender;
}

public async Task<IActionResult>


OnPost()
{
await _Sender.SubmitReview(ProductID,
Review);
return RedirectToPage("/Index");
}
}

https://www.codecademy.com/learn/learn-asp-net/modules/asp-net-dependency-injection/cheatsheet 5/8
19/01/2024, 13:10 Learn ASP.NET: ASP.NET: Dependency Injection Cheatsheet | Codecademy

Dependency

When one object (Object A) references another object // Object A - the class that depends on
(Object B), using its properties and methods, it means
that the first object (A) depends on the second (B),
Object B
making the second object (B) a dependency. class Reviewer
{
private EmailSender Sender = new
EmailSender();
public SendReview(string lesson, string
comments)
{
Sender.SendReview(lesson, comments);
}
}

// Object B - the dependency


class EmailSender
{
public SendReview(string lesson, string
comments)
{
// Send an email with the Lesson and
Comments
}
}

static void Main(string[] args)


{
Reviewer reviewer = new Reviewer().
SendReview("Dependecy Injection",
"Learned a ton!");
}

https://www.codecademy.com/learn/learn-asp-net/modules/asp-net-dependency-injection/cheatsheet 6/8
19/01/2024, 13:10 Learn ASP.NET: ASP.NET: Dependency Injection Cheatsheet | Codecademy

AddRazorPages()

Following the services.Add{ServiceName} public void


naming convention, the AddRazorPages()
ConfigureServices(IServiceCollection
method registers all the services required for the web
app to function as a Razor Pages application. services)
AddRazorPages() is called within {
Startup.ConfigureServices() . services.AddRazorPages();
If you’re curious and want to peek under the hood to
}
see all the services that are registered within
AddRazorPages() , you can find the code at
dotnet/aspnetcore. Remember, it’s all open source!

DI and IOC Container

A built-in IoC Container (Inversion of Control //Registering the Service


Container) is provided with ASP.NET that implements all
public class Startup
dependency injection functionality and allows the
developer to implement structured code following the {
Dependency Inversion (DIP) and SOLID principles. public void
The IoC Container allows the developer to register
services for injection in the
ConfigureServices(IServiceCollection
Startup.ConfigureServices() method. services)
The IoC Container handles the lifecycles of services {
and lets the developer implement classes that use the
services.AddRazorPages();
registered services to perform work.
services.AddScoped<ISendService,
SendService>();
}
}

//Injecting the service


public class ReviewModel : PageModel
{
private readonly ISendService _sender;
public ReviewModel(ISendService sender)
{
_sender = sender;
}
}

https://www.codecademy.com/learn/learn-asp-net/modules/asp-net-dependency-injection/cheatsheet 7/8
19/01/2024, 13:10 Learn ASP.NET: ASP.NET: Dependency Injection Cheatsheet | Codecademy

Print Share

https://www.codecademy.com/learn/learn-asp-net/modules/asp-net-dependency-injection/cheatsheet 8/8

You might also like