Menu
_binaryDad;
  • Me
  • Resume
_binaryDad;

Dependency injection out-of-the-box with ASP.NET 5

Posted on August 13, 2018March 21, 2021 by Ryan

I recently wrote a blog post about sharing Dependency resolvers between MVC and Web API, but I got excited to see this article from MSDN today. I’m a huge proponent of Dependency Injection to decouple service and the pluggable architecture it brings, so I’m glad to see if taking a front row seat in the upcoming .NET framework.

The article cites a handful of the types of instances it creates: singleton, scoped, transient, and “DIY” (instance) and their corresponding methods of creation (uncommented below for demonstrations purposes only). The linked article talks about these types of instances in greater detail.

namespace WebDemo
{
    public class Startup
    {
        public void Configure(IBuilder app)
        {
            app.UseServices(services =>
            {
                // Instance
                services.AddInstance<IRepository>(new DataRepository { Data = "Initialized from global" });
                // Transient
                services.AddTransient<IRepository, DataRepository>();
                // Singleton
                services.AddSingleton<IRepository, DataRepository>();
                // Scoped
                services.AddScoped<IRepository, DataRepository>();
            });
        }
    }
}

And without any other configuration, aside from the omitted/unrelated configuration for enabling MVC in the Katana Startup class, we magically have a constructor-injected instance!

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Create a simple NGINX Ingress Controller in Azure AKS
  • Fixing large image upload timeouts on WordPress
  • Install ImageMagick for PHP 7.4 on Ubuntu 18.04
  • It’s a Proud Day
  • Amazon S3 .NET SDK File Code Example

Categories

  • Azure
  • Biking
  • Code
  • Homelab
  • Kids
Mastodon
©2023 _binaryDad; | Powered by WordPress & Superb Themes