joydip_kanjilal
Contributor

How to use Lamar in ASP.Net Core

how-to
Feb 18, 20196 mins
C#Microsoft .NETSmall and Medium Business

Take advantage of Lamar, the speedy successor to StructureMap, to inject dependencies in ASP.Net Core

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.

  1. Launch the Visual Studio 2017 IDE.
  2. Click on File > New > Project.
  3. Select “ASP.Net Core Web Application (.Net Core)” from the list of templates displayed.
  4. Specify a name for the project.
  5. Click OK to save the project.
  6. A new window “New .Net Core Web Application…” is shown next.
  7. Select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top.
  8. Select API as the project template.
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that “No Authentication” is selected as we won’t be using authentication either.
  11. 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.

lamar asp.net core 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.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author