C# Dependency Injection — Service Lifetimes

What is 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.

A design methodology where rather than the caller creating the instance, it is injected by some framework or some other mechanism.

It helps to implement decoupled architecture where you change at one place and changes are reflected in many places.

Types of Dependency Lifetime

1. Singleton

Created only for the first request. If a particular instance is specified at registration time, this instance will be provided to all consumers of the registration type. Objects are the same for every request.

Used: Caching, Shared Services, Hit Counter.

2. Transient

For every request, a new instance will be created. In the same request, if we do dependency injection multiple times different instances will be injected. Objects are always different.

Used: Instances should not affect each other like different transactions, Thread safety as objects are different instances, the same object asked multiple times in the constructor.

3. Scoped

Objects are the same for a given request but different across each new request.

Used: Repository for the same transaction, Business Objects, Used most of the time.

要查看或添加评论,请登录

ramin azadi的更多文章

  • Constant vs Readonly in C#

    Constant vs Readonly in C#

    Difference Between Const and ReadOnly. One of the most important concepts that we commonly use while writing a C# code .

  • C# Delegates

    C# Delegates

    Before learning a new subject, I often ask myself some questions to improve my learning process. So, let’s start…

  • How To Read Data From An Excel Sheet

    How To Read Data From An Excel Sheet

    Step 1 Open Visual studio -> New Project -> Console App. Project Name/App Name.

  • Thread vs Task in C#

    Thread vs Task in C#

    Thread in C# The Thread class creates an actual operating system level thread in C#. The thread created with the Thread…

  • Var vs Dynamic in C#

    Var vs Dynamic in C#

    Difference between Var and Dynamic. While writing code in C# we have used Var and Dynamic keyword many times but it is…

社区洞察

其他会员也浏览了