How to use Lamar in ASP.NET Core

By FoxLearn 1/7/2025 7:55:30 AM   13
ASP.Net Core has built-in support for dependency injection (DI) with a minimal DI container.

You can also use third-party DI containers, like Lamar, which is a modern, faster alternative to the popular StructureMap container. Dependency injection is a design pattern that promotes loose coupling, making your code more testable and easier to maintain by allowing you to change implementations without altering the classes or interfaces that use them.

Benefits of Using Lamar for Dependency Injection

The main drawback of StructureMap was performance, but Lamar is lightweight and fast. It also offers a powerful API similar to StructureMap, making it easy for users familiar with StructureMap to transition to Lamar.

To use Lamar in ASP.Net Core, install the Lamar and Lamar.Microsoft.DependencyInjection NuGet packages by right-clicking on the project in Solution Explorer, select "Manage NuGet Packages…", search for the packages, and click Install.

Create the ICacheManager and CacheManager Types

In this section, we'll create the ICacheManager interface and the CacheManager class.

public interface ICacheManager
{
    void Initialize();
    bool Add<T>(string key, T obj);
    T Get<T>(string key);
}

The CacheManager class implements the ICacheManager interface and its methods.

public class CacheManager : ICacheManager
{
    public void Initialize()
    {
        // Initialization code here
    }

    public bool Add<T>(string key, T obj)
    {
        // Add to cache code here
        return true;
    }

    public T Get<T>(string key)
    {
        // Retrieve from cache code here
        return default;
    }
}

We'll use the ICacheManager interface to inject dependencies later in this example.

Configure Lamar in ASP.Net Core

The Lamar.Microsoft.DependencyInjection package exposes an extension method called UseLamar.

var builder = new WebHostBuilder();
builder.UseLamar()
       .UseUrls("http://localhost:5000")
       .UseKestrel()
       .UseStartup<Startup>();
builder.Start();

Next, open the Program.cs file, then replace the existing Program class code with the following to bootstrap the IWebHostBuilder object and use Lamar:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args)
            .UseLamar()
            .UseUrls("http://localhost:5000")
            .Build()
            .Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
               .UseStartup<Startup>();
}

Bootstrap the Lamar Container in ASP.NET Core

Now, 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<ICacheManager, CacheManager>();
    });
}

The ConfigureContainer method, as shown below, illustrates how this works:

public void ConfigureContainer(ServiceRegistry services)
{
    services.Scan(s =>
    {
        s.TheCallingAssembly();
        s.WithDefaultConventions();
    });
}

Use the CacheManager Instance in Controller Methods via Dependency Injection

Now, you can use the CacheManager instance in controller classes.

Right-click the Controllers solution folder of your ASP.Net Core project, and replace the generated code with the following:

[Route("api/[controller]")]
[ApiController]
public class DefaultController : ControllerBase
{
    private ICacheManager _cacheManager;

    public DefaultController(ICacheManager cacheManager)
    {
        _cacheManager = cacheManager;
    }

    // Other controller methods
}

ASP.Net Core has a built-in, out-of-the-box dependency injection container, but it has some limitations. You can easily integrate third-party containers like Lamar, which is a faster, more flexible alternative to the default DI container.