{"id":1736,"date":"2023-06-14T08:24:49","date_gmt":"2023-06-14T08:24:49","guid":{"rendered":"http:\/\/waqar-arshad.com\/?p=1736"},"modified":"2023-06-14T08:25:17","modified_gmt":"2023-06-14T08:25:17","slug":"asp-net-core-dependency-injection","status":"publish","type":"post","link":"http:\/\/waqar-arshad.com\/index.php\/2023\/06\/14\/asp-net-core-dependency-injection\/","title":{"rendered":"Asp.Net Core Dependency Injection"},"content":{"rendered":"<div class=\"pld-like-dislike-wrap pld-template-1\">\r\n    <div class=\"pld-like-wrap  pld-common-wrap\">\r\n    <a href=\"javascript:void(0)\" class=\"pld-like-trigger pld-like-dislike-trigger  \" title=\"\" data-post-id=\"1736\" data-trigger-type=\"like\" data-restriction=\"cookie\" data-already-liked=\"0\">\r\n                        <i class=\"fas fa-thumbs-up\"><\/i>\r\n                <\/a>\r\n    <span class=\"pld-like-count-wrap pld-count-wrap\">    <\/span>\r\n<\/div><div class=\"pld-dislike-wrap  pld-common-wrap\">\r\n    <a href=\"javascript:void(0)\" class=\"pld-dislike-trigger pld-like-dislike-trigger  \" title=\"\" data-post-id=\"1736\" data-trigger-type=\"dislike\" data-restriction=\"cookie\" data-already-liked=\"0\">\r\n                        <i class=\"fas fa-thumbs-down\"><\/i>\r\n                <\/a>\r\n    <span class=\"pld-dislike-count-wrap pld-count-wrap\"><\/span>\r\n<\/div><\/div>\n<p>ASP.NET Core &#8211; Dependency Injection<\/p>\n\n\n\n<p>ASP.NET Core is designed from scratch to support&nbsp;<a href=\"https:\/\/www.tutorialsteacher.com\/ioc\/dependency-injection\">Dependency Injection<\/a>. ASP.NET Core injects objects of dependency classes through constructor or method by using built-in&nbsp;<a href=\"https:\/\/www.tutorialsteacher.com\/ioc\/ioc-container\">IoC container<\/a>.<\/p>\n\n\n\n<p>Built-in IoC Container<\/p>\n\n\n\n<p>ASP.NET Core framework contains simple out-of-the-box IoC container which does not have as many features as other third party IoC containers. If you want more features such as auto-registration, scanning, interceptors, or decorators then you may replace built-in IoC container with a third party container.<\/p>\n\n\n\n<p>The built-in container is represented by&nbsp;IServiceProvider&nbsp;implementation that supports constructor injection by default. The types (classes) managed by built-in IoC container are called&nbsp;<strong>services<\/strong>.<\/p>\n\n\n\n<p>There are basically two types of services in ASP.NET Core:<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\">\n<li>Framework Services: Services which are a part of ASP.NET Core framework such as IApplicationBuilder, IHostingEnvironment, ILoggerFactory etc.<\/li>\n\n\n\n<li>Application Services: The services (custom types or classes) which you as a programmer create for your application.<\/li>\n<\/ol>\n\n\n\n<p>In order to let the IoC container automatically inject our application services, we first need to register them with IoC container.<\/p>\n\n\n\n<p>Registering Application Service<\/p>\n\n\n\n<p>Consider the following example of simple&nbsp;ILog&nbsp;interface and its implementation class. We will see how to register it with built-in IoC container and use it in our application.<\/p>\n\n\n\n<p>public interface ILog<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; void info(string str);<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>class MyConsoleLogger : ILog<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public void info(string str)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.WriteLine(str);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>ASP.NET Core allows us to register our application services with IoC container, in the&nbsp;ConfigureServices&nbsp;method of the Startup class. The&nbsp;ConfigureServices&nbsp;method includes a parameter of&nbsp;IServiceCollection&nbsp;type which is used to register application services.<\/p>\n\n\n\n<p>Let&#8217;s register above&nbsp;ILog&nbsp;with IoC container in ConfigureServices() method as shown below.<\/p>\n\n\n\n<p>Example: Register Service<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public class Startup<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public void ConfigureServices(IServiceCollection services)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger()));&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; \/\/ other code removed for clarity..<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>As you can see above,&nbsp;Add()&nbsp;method of&nbsp;IServiceCollection&nbsp;instance is used to register a service with an IoC container. The&nbsp;<a href=\"https:\/\/docs.microsoft.com\/en-us\/aspnet\/core\/api\/microsoft.extensions.dependencyinjection.servicedescriptor\" target=\"_blank\" rel=\"noreferrer noopener\">ServiceDescriptor<\/a>&nbsp;is used to specify a service type and its instance. We have specified&nbsp;ILog&nbsp;as service type and&nbsp;MyConsoleLogger&nbsp;as its instance. This will register&nbsp;ILog&nbsp;service as a singleton by default. Now, an IoC container will create a singleton object of&nbsp;MyConsoleLogger&nbsp;class and inject it in the constructor of classes wherever we include&nbsp;ILog&nbsp;as a constructor or method parameter throughout the application.<\/p>\n\n\n\n<p>Thus, we can register our custom application services with an IoC container in ASP.NET Core application. There are other extension methods available for quick and easy registration of services which we will see later in this chapter.<\/p>\n\n\n\n<p>Understanding Service Lifetime<\/p>\n\n\n\n<p>Built-in IoC container manages the lifetime of a registered service type. It automatically disposes a service instance based on the specified lifetime.<\/p>\n\n\n\n<p>The built-in IoC container supports three kinds of lifetimes:<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\">\n<li><strong>Singleton:<\/strong>&nbsp;IoC container will create and share a single instance of a service throughout the application&#8217;s lifetime.<\/li>\n\n\n\n<li><strong>Transient:<\/strong>&nbsp;The IoC container will create a new instance of the specified service type every time you ask for it.<\/li>\n\n\n\n<li><strong>Scoped:<\/strong>&nbsp;IoC container will create an instance of the specified service type once per request and will be shared in a single request.<\/li>\n<\/ol>\n\n\n\n<p>The following example shows how to register a service with different lifetimes.<\/p>\n\n\n\n<p>Example: Register a Service with Lifetime<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public void ConfigureServices(IServiceCollection services)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger()));&nbsp;&nbsp;&nbsp; \/\/ singleton<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; services.Add(new ServiceDescriptor(typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Transient)); \/\/ Transient<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; services.Add(new ServiceDescriptor(typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Scoped));&nbsp;&nbsp;&nbsp; \/\/ Scoped<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Extension Methods for Registration<\/p>\n\n\n\n<p>ASP.NET Core framework includes extension methods for each types of lifetime;&nbsp;AddSingleton(),&nbsp;AddTransient()&nbsp;and&nbsp;AddScoped()&nbsp;methods for singleton, transient and scoped lifetime respectively.<\/p>\n\n\n\n<p>The following example shows the ways of registering types (service) using extension methods.<\/p>\n\n\n\n<p>Example: Extension Methods<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public void ConfigureServices(IServiceCollection services)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; services.AddSingleton&lt;ILog, MyConsoleLogger&gt;();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; services.AddSingleton(typeof(ILog), typeof(MyConsoleLogger));<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; services.AddTransient&lt;ILog, MyConsoleLogger&gt;();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; services.AddTransient(typeof(ILog), typeof(MyConsoleLogger));<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; services.AddScoped&lt;ILog, MyConsoleLogger&gt;();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; services.AddScoped(typeof(ILog), typeof(MyConsoleLogger));<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Constructor Injection<\/p>\n\n\n\n<p>Once we register a service, the IoC container automatically performs constructor injection if a service type is included as a parameter in a constructor.<\/p>\n\n\n\n<p>For example, we can use&nbsp;ILog&nbsp;service type in any MVC controller. Consider the following example.<\/p>\n\n\n\n<p>Example: Using Service<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public class HomeController : Controller<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; ILog _log;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public HomeController(ILog log)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _log = log;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public IActionResult Index()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _log.info(&#8220;Executing \/home\/index&#8221;);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return View();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>In the above example, an IoC container will automatically pass an instance of&nbsp;MyConsoleLogger&nbsp;to the constructor of&nbsp;HomeController. We don&#8217;t need to do anything else. An IoC container will create and dispose an instance of&nbsp;ILog&nbsp;based on the registered lifetime.<\/p>\n\n\n\n<p>Action Method Injection<\/p>\n\n\n\n<p>Sometimes we may only need dependency service type in a single action method. For this, use [FromServices] attribute with the service type parameter in the method.<\/p>\n\n\n\n<p>Example: Action Method Injection<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>using Microsoft.AspNetCore.Mvc;<\/p>\n\n\n\n<p>public class HomeController : Controller<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public HomeController()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public IActionResult Index([FromServices] ILog log)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; log.info(&#8220;Index method executing&#8221;);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return View();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Property Injection<\/p>\n\n\n\n<p>Built-in IoC container does not support property injection. You will have to use third party IoC container.<\/p>\n\n\n\n<p>Get Services Manually<\/p>\n\n\n\n<p>It is not required to include dependency services in the constructor. We can access dependent services configured with built-in IoC container manually using&nbsp;RequestServices&nbsp;property of&nbsp;HttpContext&nbsp;as shown below.<\/p>\n\n\n\n<p>Example: Get Service Instance Manually<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public class HomeController : Controller<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public HomeController()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public IActionResult Index()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var services = this.HttpContext.RequestServices;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var log = (ILog)services.GetService(typeof(ILog));<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; log.info(&#8220;Index method executing&#8221;);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return View();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>It is recommended to use constructor injection instead of getting it using&nbsp;RequestServices.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>ASP.NET Core &#8211; Dependency Injection ASP.NET Core is designed from scratch to support&nbsp;Dependency Injection. ASP.NET Core injects objects of dependency classes through constructor or method by using built-in&nbsp;IoC container. Built-in IoC Container ASP.NET Core framework contains simple out-of-the-box IoC container which does not have as many features as other third party IoC containers. If you [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[13,1],"tags":[],"class_list":["post-1736","post","type-post","status-publish","format-standard","hentry","category-asp-net-core","category-uncategorized"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"admin","author_link":"http:\/\/waqar-arshad.com\/index.php\/author\/waqar_29_1\/"},"uagb_comment_info":30,"uagb_excerpt":"ASP.NET Core &#8211; Dependency Injection ASP.NET Core is designed from scratch to support&nbsp;Dependency Injection. ASP.NET Core injects objects of dependency classes through constructor or method by using built-in&nbsp;IoC container. Built-in IoC Container ASP.NET Core framework contains simple out-of-the-box IoC container which does not have as many features as other third party IoC containers. If you&hellip;","_links":{"self":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts\/1736","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/comments?post=1736"}],"version-history":[{"count":1,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts\/1736\/revisions"}],"predecessor-version":[{"id":1737,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts\/1736\/revisions\/1737"}],"wp:attachment":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/media?parent=1736"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/categories?post=1736"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/tags?post=1736"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}