TinyIoC is a lightweight and fast inversion of control container that makes dependency injection simple and easy. Here’s how to take advantage of it in ASP.NET Core applications. Credit: Thinkstock When working with dependency injection and inversion of control in ASP.NET Core applications, you might often need a IoC container that is simple or lightweight to avoid unnecessary complexity or unnecessary overhead. Most IoC containers consume a lot of resources—not ideal when you don’t need a full-fledged IoC container in your application. In this article we’ll discuss the concepts of inversion of control and dependency injection and introduce TinyIoC, an IoC container that is both simple and lightweight. Then we’ll demonstrates how we can work with TinyIoC in ASP.NET Core applications. To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here. Inversion of control and dependency injection The inversion of control (IoC) and dependency injection (DI) architectural patterns help you enhance the modularity, testability, and maintainability of your application. IoC is a design pattern that enables you to decouple components, substitute dependency implementations, and facilitate testing. DI is a subset of the IoC principle and serves as one method of implementing IoC. In addition to DI, there are several alternative techniques to implement IoC such as events, delegates, template patterns, factory methods, and service locators. In the sections that follow, we’ll examine how we can work with TinyIoC in ASP.NET Core. Before we get started, let’s create a new ASP.NET Core Web API project in Visual Studio. We’ll use this project in the subsequent sections of this article. Create an ASP.NET Core Web API project in Visual Studio 2022 To create an ASP.NET Core Web API project in Visual Studio 2022, follow the steps outlined below. Launch the Visual Studio 2022 IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences. Click Next. In the “Additional Information” window shown next, leave the “Use controllers (uncheck to use minimal APIs)” box checked. We won’t be using minimal APIs in this project. Elsewhere in the “Additional Information” window, leave the “Authentication Type” set to “None” (the default) and make sure the check boxes “Enable Open API Support,” “Configure for HTTPS,” and “Enable Docker” remain unchecked. We won’t be using any of those features here. Click Create. We’ll use this ASP.NET Core Web API project to work TinyIoC in the sections below. Install the TinyIoC NuGet package Next add the TinyIoC NuGet package to the Web API project you just created in Visual Studio. Select the project in the Solution Explorer window and right-click and select “Manage NuGet Packages.” In the NuGet Package Manager window, search for the TinyIoC package and install it. Alternatively, you can install the TinyIoC package via the NuGet Package Manager console by entering the line shown below. PM> Install-Package TinyIoC Because we’re working with .NET Core, we should use the TinyIoC Release Candidate NuGet package. You should check the “Include prerelease” check box in the “Manage NuGet Packages…” window and install the latest TinyIoC RC NuGet package version as shown in Figure 1 below. IDG Figure 1: Installing TinyIoC RC for ASP.NET Core. Create a minimalistic class in ASP.NET Core In this example, we’ll create a minimalistic class which we’ll use as a dependency in the API controller we’ll create later. To do this, create a new class named MyService and replace the generated code with the following code listing. using System.Diagnostics; namespace TinyIoC_Demo { public class MyService : IMyService { public string MyMethod() { Trace.WriteLine("Inside MyMethod()"); return "Hello World"; } } } The IMyService interface contains the declaration of the method named MyMethod. namespace TinyIoC_Demo { public interface IMyService { public string MyMethod(); } } Configure a TinyIoC container in ASP.NET Core To register services using the TinyIoC container in ASP.NET Core, you should write the following piece of code in the Program.s file of the project we created earlier. TinyIoCContainer.Current.Register<IMyService, MyService>().AsSingleton(); If you have multiple dependencies to register with the container, you can write them inside a method and then call it here once to ensure that the code is clean. internal static class Bootstrap { internal static void RegisterDependencies() { TinyIoCContainer.Current.Register <IMyService, MyService>().AsSingleton(); //Write code here to register the other services } } You can now invoke the RegisterDependencies method of the Bootstrap class to register the services with the built-in container of the ASP.NET Core runtime as shown below. Bootstrap.RegisterDependencies(); You can optionally provide a name when registering the service with the container as shown in the code snippet given below. var myServiceInstance = new MyService(); TinyIoCContainer.Current.Register<IMyService>(myServiceInstance, "MyService"); Complete source code of Program.cs The complete source code of the Program.cs file is given below for your reference. using TinyIoC; using TinyIoC_Demo; var builder = WebApplication.CreateBuilder(args); // Add services to the container. Bootstrap.RegisterDependencies(); builder.Services.AddControllers(); var app = builder.Build(); // Configure the HTTP request pipeline. app.UseAuthorization(); app.MapControllers(); app.Run(); internal static class Bootstrap { internal static void RegisterDependencies() { TinyIoCContainer.Current.Register <IMyService, MyService>().AsSingleton(); //Write code here to register the other services } } Resolve dependencies in ASP.NET Core Once dependencies are registered and added to the container, you should be able to retrieve the dependencies in your application and use them to invoke methods. To resolve the dependencies, you can use the Resolve method of the TinyIoCContainer class as shown in the code snippet given below. var _myService = TinyIoCContainer.Current.Resolve<IMyService>(); Note how the type has been passed to retrieve the appropriate type of object from the container. You can now use this instance (named _myService) to invoke methods pertaining to the IMyService interface. Create an API controller in ASP.NET Core Create a new API controller and replace the generated source code with the following code listing. using Microsoft.AspNetCore.Mvc; using TinyIoC; namespace TinyIoC_Demo.Controllers { [Route("api/[controller]")] [ApiController] public class TinyIOCDemoController : ControllerBase { private readonly IMyService _myService; public TinyIOCDemoController() { _myService = TinyIoCContainer.Current.Resolve<IMyService>(); } [HttpGet] public ActionResult Get() { return Ok(_myService.MyMethod()); } } } When you set a breakpoint in the HttpGet action method and run the application, you’ll see that the instance of type IMyService has been resolved properly in the controller and is available in the action method. IDG Figure 2: The TinyIoC container at work! Conclusion For the sake of simplicity, we’ve created a minimalistic implementation of the TinyIoC container in ASP.NET Core. You can explore the unit tests provided here to learn more about how you can leverage the TinyIoC container. You can also build your own custom IoC container. I’ll explore this in a future article here. Related content news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks news Akka distributed computing platform adds Java SDK Akka enables development of applications that are primarily event-driven, deployable on Akka’s serverless platform or on AWS, Azure, or GCP cloud instances. By Paul Krill Nov 18, 2024 2 mins Java Scala Serverless Computing news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks how-to How to use DispatchProxy for AOP in .NET Core Take advantage of the DispatchProxy class in C# to implement aspect-oriented programming by creating proxies that dynamically intercept method calls. By Joydip Kanjilal Nov 14, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks Resources Videos