How to use Lamar in ASP. Net core web application or Web API

In this article, we will learn How to use Lamar in ASP. Net core web application or Web API.

Why we use Lamar to implement dependency injection: There are lots of dependency injection containers in the .Net technology. The biggest disadvantage is the performance problem. The Lamar in this article is very lightweight and provides rich APIs to call.

In startup files, we need to add all services or repositories references, suppose we have more than 100 then it makes the file too big. One more thing when we add a new service then each time we need to add that reference in startup.cs that is not good practice or totally time wast.

What to do in code.

In Project time add 2 packages

<PackageReference Include="Lamar" Version="4.2.1" />
<PackageReference Include="Lamar.Microsoft.DependencyInjection" Version="4.1.5" />

In startup.cs file do this

        public void ConfigureServices(IServiceCollection services)
        { 
            services.AddLamar(new LamarRegistry());

        }

Then add a new class in a project using the below code. Must change YourProjectName.

public class LamarRegistry : ServiceRegistry
    {
        public LamarRegistry()
        {
            Scan(scanner =>
            {
                scanner.TheCallingAssembly();
                scanner.WithDefaultConventions();
                scanner.AssembliesAndExecutablesFromApplicationBaseDirectory(assembly =>
                    assembly.GetName().Name.StartsWith("YourProjectName."));
            });

        }
    }

Then in the program.cs file do this.

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args).UseLamar()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

Lamar working is ready to use you may use now.