Take advantage of Lamar, the speedy successor to StructureMap, to inject dependencies in ASP.Net Core Credit: Rawpixel ASP.Net Core comes with built-in support for dependency injection. In fact, ASP.Net Core comes with a minimalistic dependency injection container out of the box. However, you can also use third-party dependency injection containers in ASP.Net Core. Dependency injection is a design pattern that facilitates loose coupling and promotes testability and maintenance. You can take advantage of dependency injection to improve your implementations without having to change the classes or interfaces that use those implementations. Lamar is a fast, modernized successor of the popular inversion-of-control (IoC) container StructureMap. This article discusses how we can work with Lamar in ASP.Net Core. Why use Lamar for dependency injection The main drawback of StructureMap was performance. Lamar is lightweight and fast. Lamar also has a powerful API that enables you to explore and leverage its features easily. The Lamar API is similar to StructureMap, so if you have used StructureMap in the past you will be able to use Lamar with ease. It is quite easy to set up Lamar in ASP.Net Core. We just need to install the necessary packages from NuGet, specify the bootstrapping code in Program.cs, and then add the necessary dependencies in the Startup.cs file — the same way you do with the default dependency injection container of ASP.Net Core. Create an ASP.Net Core project First off, let’s create an ASP.Net Core project. If Visual Studio 2017 is up and running in your system, follow the steps given below to create a new ASP.Net Core project in Visual Studio. Launch the Visual Studio 2017 IDE. Click on File > New > Project. Select “ASP.Net Core Web Application (.Net Core)” from the list of templates displayed. Specify a name for the project. Click OK to save the project. A new window “New .Net Core Web Application…” is shown next. Select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top. Select API as the project template. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that “No Authentication” is selected as we won’t be using authentication either. Click OK. This would create a new ASP.NET Core project in Visual Studio. Next, we should install the necessary NuGet packages for using Lamar with this project. Install the Lamar NuGet packages To work with Lamar in ASP.Net Core, you will need to have the Lamar and Lamar.Microsoft.DependencyInjection packages installed in your project. To install these packages, right-click on the project in the Solution Explorer window and select “Manage NuGet Packages…”. Then you can search for these packages and click on Install. IDG The two packages needed for working with Lamar in ASP.Net Core are Lamar and Lamar.Microsoft.DependencyInjection. An alternative to installing these packages using the NuGet Package Manager is to use the NuGet Package Manager console window. To install these packages using the NuGet Package Manager console window, enter the following commands one after the other at the console. Install-Package Lamar -Version 2.1.0 Install-Package Lamar.Microsoft.DependencyInjection -Version 2.1.0 Create the IDBManager and DBManager types In this section we’ll create the IDBManager and the DBManager types. The following code snippet illustrates the IDBManager interface, which we’ll use later for dependency injection. public interface IDBManager { void Initialize(); bool Save<T>(T obj); } The DBManager class extends the IDBManager interface and implements its methods. public class DBManager: IDBManager { public void Initialize() { //Write some initialization code here } public bool Save<T>(T obj) { //Write your code here return true; } } We’ll take advantage of the IDBManager interface to inject dependency later in this article. Configure Lamar in ASP.Net Core The package Lamar.Microsoft.DependencyInjection exposes an extension method called UseLamar. This extension method is called to introduce Lamar to the application’s infrastructure. Refer to the code listing below that illustrates how this can be achieved. var builder = new WebHostBuilder(); builder.UseLamar() .UseUrls("http://localhost:50533") .UseKestrel() .UseStartup<Startup>(); builder.Start(); Next, open the file Program.cs. The code snippet below shows the initial contents of this file, which we’ll alter in the next step. Note that this file is created by the runtime automatically when you create an ASP.Net Core project. public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } Now, replace the source code of the Program class (generated by default as shown above) with the following code to bootstrap the IWebHostBuilder object. public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args) .UseLamar() .UseUrls("http://localhost:50533") .Build() .Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } Bootstrap the Lamar container in ASP.Net Core Next, you can add services to the pipeline in the ConfigureServices method of the Startup class as shown below. public void ConfigureServices(IServiceCollection services) { var container = new Container(x => { x.AddTransient<IDBManager, DBManager>(); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } Thanks to the Auto Wiring support in Lamar, Lamar searches for the constructors of the requested and needed types and builds the instances. The ConfigureContainer method shown below illustrates how this is achieved. public void ConfigureContainer(ServiceRegistry services) { services.Scan(s => { s.TheCallingAssembly(); s.WithDefaultConventions(); }); } Use the DBManager instance in Controller methods via dependency injection And, that’s it! You can now leverage the DBManager instance in the controller classes. To do that, right click on the Controllers solution folder of the ASP.Net Core project you created earlier. Next, replace the generated code with the following code. [Route("api/[controller]")] [ApiController] public class DefaultController : ControllerBase { private IDBManager _dbManager; public DefaultController(IDBManager dbManager) { _dbManager = dbManager; } //Other controller methods } ASP.Net Core comes with an out-of-the-box, built-in dependency injection container, but it has limited capabilities. You can easily use third-party containers in ASP.Net Core as well. Lamar is one such IoC container — a snappier replacement for the StructureMap IoC container. Related content how-to How to use FastEndpoints in ASP.NET Core Take advantage of the free open-source FastEndpoints library to build fast and lean APIs in your ASP.NET Core applications. By Joydip Kanjilal Jul 11, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks how-to How to use Refit to consume APIs in ASP.NET Core Take advantage of Refit REST library to simplify API consumption and make your code cleaner, more efficient, and easier to maintain. By Joydip Kanjilal Jul 04, 2024 10 mins C# Microsoft .NET Software Deployment how-to When to use an abstract class vs. interface in C# Understanding the differences between an abstract class and interface is key to designing loosely coupled and extensible applications. By Joydip Kanjilal Jun 20, 2024 10 mins Small and Medium Business Microsoft .NET C# how-to 6 security best practices for ASP.NET Core Learn the best practices and built-in safeguards for preventing attacks and protecting sensitive data in your ASP.NET Core web applications. By Joydip Kanjilal Jun 07, 2024 6 mins C# Microsoft .NET Web Development Resources Videos