{"id":6433,"date":"2016-03-28T18:40:14","date_gmt":"2016-03-28T18:40:14","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/webdev\/?p=6433"},"modified":"2016-03-28T18:40:14","modified_gmt":"2016-03-28T18:40:14","slug":"dependency-injection-in-asp-net-core","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/dotnet\/dependency-injection-in-asp-net-core\/","title":{"rendered":"Dependency Injection in ASP.NET Core"},"content":{"rendered":"<p>In a recent Community Standup, one of the questions that was asked of the team was: &#8220;How do I get started with Dependency Injection in ASP.NET Core?&#8221;\u00a0 This is where we&#8217;re going to answer your question, because in this post we&#8217;re going to share how dependency injection is used in ASP.NET Core and how you can configure it to meet your needs.<!--more--><\/p>\n<h3>A Primer<\/h3>\n<p>Dependency Injection is an application design that enables class dependencies to be automatically added to an instantiated object.\u00a0 The net effect is a loose coupling between classes, with dependencies provided to a class as constructor parameters or properties.\u00a0 These parameters or properties typically reference an interface so that a concrete object that implements that interface can be passed in.\u00a0 Consider the following class design:<\/p>\n<p>This overly simple tax calculator class requires an ITaxingAuthorityRules object to be passed in to it in order to be created.\u00a0 This interface implements a method called &#8220;CalculateTax&#8221; and returns a decimal.\u00a0 In the use of this tax calculator class, I could pass in different implementations of the ITaxingAuthorityRules for different countries or for a personal tax versus a corporate tax or even pass in a fake object for the purposes of testing the CalculateTaxesDue method.\u00a0 The promise of this approach is this decoupling of resources that no longer need to know how they are being used, but can be focused on doing one thing and doing it well.\u00a0 We continue to use our TaxCalculator into the future with new taxing rules. In using the Dependency Injection design, its a common practice to use a container object that is used to construct all of the objects that will be used in the application.\u00a0 This container is configured with knowledge of many of the default interface to concrete class mappings so that as interfaces are requested by new classes an appropriate class can be created and injected into the new class.<\/p>\n<h3>Dependency Injection in ASP.NET Core<\/h3>\n<p>With ASP.NET Core, dependency injection is a fundamental tenet of the framework.\u00a0 All classes instantiated by the framework are done so through the container service that is maintained by the framework in a container and configured by default in the Startup\/ConfigureServices method. This method looks like the following in an RC1 default template:<\/p>\n<p>In this code, an EntityFramework context, the identity configuration, the MVC framework, and mappings for an IEmailSender and ISmsSender are configured for the dependency injection container to be able to inject into other classes that it creates.\u00a0 The IServiceCollection object passed into this method has a number of methods and extension methods connected to it that enable this simple mapping and registration of services.\u00a0 Typically when you want to register your own mappings with the container, you will use either the AddTransient or AddSingleton methods register your mappings.\u00a0 The AddTransient method instructs the container to create a new instance of the designated class for each instance of each created class that requires it.\u00a0 AddSingleton creates one instance and passes that instance into each created class that requires it.\u00a0 More details about configuring the container are available in the <a href=\"https:\/\/docs.asp.net\/en\/latest\/fundamentals\/dependency-injection.html\" target=\"_blank\" rel=\"noopener noreferrer\">ASP.NET Core docs<\/a>.<\/p>\n<p>I like to add the Configuration that was built in the constructor of the Startup class to the container with a statement in the ConfigureServices methods to reads like the following:<\/p>\n<pre>services.AddSingleton&lt;IConfiguration&gt;(_ =&gt; Configuration);<\/pre>\n<p>This will stash the current value of the Configuration property in the container and make the configuration accessible to my entire project when I need it.<\/p>\n<h4>Controllers<\/h4>\n<p>Controllers are very easy to inject dependencies into, and a great example is the constructor for the default AccountController:<\/p>\n<p>This constructor accepts five input parameters and places their values into private readonly fields. These parameters were all configured by the ConfigureServices methods, except for the ILoggerFactory. This interface, along with the IApplicationBuilder and IHostingEnvironment are added to the container by the ASP.NET framework.\u00a0 Without having to write methods to configure and load each of these dependencies, our AccountController class can start working with them.<\/p>\n<h4>Views<\/h4>\n<p>The Views in our project can have objects injected into them by the container by using the new @inject directive:<\/p>\n<p>The syntax indicates that the first argument is the type to require and the second argument is the variable name that will be exposed to the rest of the razor page.<\/p>\n<h3>Other Containers<\/h3>\n<p><img decoding=\"async\" class=\"alignright wp-image-6451 size-medium\" src=\"https:\/\/devblogs.microsoft.com\/aspnet\/wp-content\/uploads\/sites\/16\/2016\/03\/container-158362_960_720-300x150-1.png\" alt=\"Containers to the rescue!\" width=\"300\" height=\"150\" \/>The default ASP.NET container is simple and does not offer the robust configuration and performance options that are available with other containers.\u00a0 Fortunately, you can swap out the default container with one of the community-created full featured ones that is already available as a NuGet package.\u00a0 Autofac is one that is already available for ASP.NET Core, and you can add it to your project by referencing both the Autofac and Autofac.Extensions.DependencyInjection packages.\u00a0 Next, change the signature of the ConfigureServices method to return an IServiceProvider.\u00a0 Finally, add some configuration code at the end of the method to copy the registered services over to Autofac and register it as the new service provider:<\/p>\n<p>Very cool&#8230; now my web application is using Autofac to resolve dependencies.<\/p>\n<h3>Summary<\/h3>\n<p>Dependency Injection is a design pattern for your classes.\u00a0 ASP.NET Core makes it easy to get started with this design pattern by shipping a container that you can use with your application.\u00a0 Configure your application&#8217;s controllers, views, and other classes that are instantiated by the framework with parameters on the constructor method to have those types automatically created and passed in to your class.\u00a0 You can learn more about <a href=\"https:\/\/docs.asp.net\/en\/latest\/fundamentals\/dependency-injection.html\" target=\"_blank\" rel=\"noopener noreferrer\">ASP.NET Dependency Injection<\/a> from our documentation.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In a recent Community Standup, one of the questions that was asked of the team was: &#8220;How do I get started with Dependency Injection in ASP.NET Core?&#8221;\u00a0 This is where we&#8217;re going to answer your question, because in this post we&#8217;re going to share how dependency injection is used in ASP.NET Core and how you [&hellip;]<\/p>\n","protected":false},"author":405,"featured_media":58792,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[197,7509],"tags":[7469],"class_list":["post-6433","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-aspnet","category-aspnetcore","tag-dependency-injection"],"acf":[],"blog_post_summary":"<p>In a recent Community Standup, one of the questions that was asked of the team was: &#8220;How do I get started with Dependency Injection in ASP.NET Core?&#8221;\u00a0 This is where we&#8217;re going to answer your question, because in this post we&#8217;re going to share how dependency injection is used in ASP.NET Core and how you [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/6433","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/users\/405"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/comments?post=6433"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/6433\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media\/58792"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media?parent=6433"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/categories?post=6433"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/tags?post=6433"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}