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 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 news Visual Studio 17.12 brings C++, Copilot enhancements Debugging and productivity improvements also feature in the latest release of Microsoft’s signature IDE, built for .NET 9. By Paul Krill Nov 13, 2024 3 mins Visual Studio Integrated Development Environments Microsoft .NET news Microsoft’s .NET 9 arrives, with performance, cloud, and AI boosts Cloud-native apps, AI-enabled apps, ASP.NET Core, Aspire, Blazor, MAUI, C#, and F# all get boosts with the latest major rev of the .NET platform. By Paul Krill Nov 12, 2024 4 mins C# Generative AI Microsoft .NET news .NET vector data abstractions library now available in preview The abstractions library allows developers and library authors to perform CRUD operations and searches on vector stores. By Paul Krill Nov 06, 2024 1 min Microsoft .NET Generative AI Software Development Resources Videos