- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 can we inject the service dependency into the controller C# Asp.net Core?
ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container.
The built-in container is represented by IServiceProvider implementation that supports constructor injection by default. The types (classes) managed by built-in IoC container are called services.
In order to let the IoC container automatically inject our application services, we first need to register them with IoC container.
Example
public interface ILog{ void info(string str); } class MyConsoleLogger : ILog{ public void info(string str){ Console.WriteLine(str); } }
ASP.NET Core allows us to register our application services with IoC container, in the ConfigureServices method of the Startup class. The ConfigureServices method includes a parameter of IServiceCollection type which is used to register application services
Register ILog with IoC container in ConfigureServices() method as shown below.
public class Startup{ public void ConfigureServices(IServiceCollection services){ services.AddSingleton<ILog, MyConsoleLogger>(); } }
Add() method of IServiceCollection instance is used to register a service with an IoC container
We have specified ILog as service type and MyConsoleLogger as its instance This will register ILog service as a singleton Now, an IoC container will create a singleton object of MyConsoleLogger class and inject it in the constructor of classes wherever we include ILog as a constructor or method parameter throughout the application.
- Related Articles
- How to specify service lifetime for register service that added as a dependency C# Asp.net Core?
- How can we test C# Asp.Net WebAPI?
- How to enable Session in C# ASP.NET Core?
- What is Kestral C# Asp.net Core?
- What are the benefits of choosing ASP.NET Core over ASP.NET?
- How C# ASP.NET Core Middleware is different from HttpModule?
- How to handle errors in middleware C# Asp.net Core?
- What is the use of UseIISIntegration in C# Asp.net Core?
- What is routing in C# ASP.NET Core?
- What is Metapackage in C# Asp.net Core?
- What is ASP.NET Core? Explain how it's different from the ASP.NET framework.
- Explain how logging works in ASP.NET Core
- How do you configure ASP.NET Core applications?
- What is the difference between IApplicationBuilder.Use() and IApplicationBuilder.Run() C# Asp.net Core?
- What are the various JSON files available in C# ASP.NET Core?
