
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Inject Service Dependency into Controller in 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.