- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to specify service lifetime for register service that added as a dependency C# Asp.net Core?
Built-in IoC container manages the lifetime of a registered service type. It automatically disposes a service instance based on the specified lifetime.
The built-in IoC container supports three kinds of lifetimes −
Singleton − IoC container will create and share a single instance of a service throughout the application's lifetime.
Transient − The IoC container will create a new instance of the specified service type every time you ask for it.
Scoped − IoC container will create an instance of the specified service type once per request and will be shared in a single request.
Example
public interface ILog{ void info(string str); } class MyConsoleLogger : ILog{ public void info(string str){ Console.WriteLine(str); } }
public class Startup{ public void ConfigureServices(IServiceCollection services){ services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger())); // singleton services.Add(new ServiceDescriptor(typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Transient)); // Transient services.Add(new ServiceDescriptor(typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Scoped)); // Scoped } }
The following example shows the ways of registering types (service) using extension methods.
public class Startup{ public void ConfigureServices(IServiceCollection services){ services.AddSingleton<ILog, MyConsoleLogger>(); services.AddSingleton(typeof(ILog), typeof(MyConsoleLogger)); services.AddTransient<ILog, MyConsoleLogger>(); services.AddTransient(typeof(ILog), typeof(MyConsoleLogger)); services.AddScoped<ILog, MyConsoleLogger>(); services.AddScoped(typeof(ILog), typeof(MyConsoleLogger)); } }
Advertisements