Dependency injection (DI) is a software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.
A fast IoC container heavily optimized for usage within ASP.Net Core and other .Net server-side applications. The successor to the venerable StructureMap library, the original IoC tool for .Net.
Go to Program.cs and add UseLamar() in the CreateHostBuilder method.
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.UseLamar() //Add this line
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Add an interface named IInstaller, to be used for configuring various services for your solution.
using Lamar;
using Microsoft.Extensions.Configuration;
namespace Project.Web.Installers
{
internal interface IInstaller
{
void InstallServices(ServiceRegistry services, IConfiguration configuration);
}
}
Add a class named InstallerExtensions with the below code.
using Lamar;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Project.Web.Installers
{
public static class InstallerExtensions
{
public static void InstallServicesInAssembly(this ServiceRegistry services, IConfiguration configuration)
{
List<IInstaller> installers = typeof(Startup).Assembly.ExportedTypes.Where(x =>
typeof(IInstaller).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract).Select(Activator.CreateInstance).Cast<IInstaller>().ToList();
installers.ForEach(installer => installer.InstallServices(services, configuration));
}
}
}
Go to Startup.cs and add the ConfigureContainer method to the class.
public void ConfigureContainer(ServiceRegistry services)
{
services.InstallServicesInAssembly(Configuration);
// for Lamar IOC, add all assemblies for the project but ignore Test assemblies
services.Scan(s =>
{
s.AssembliesFromApplicationBaseDirectory(assembly =>
assembly.GetName().Name.Contains("Project", StringComparison.OrdinalIgnoreCase) &&
!assembly.GetName().Name.Contains("Tests", StringComparison.OrdinalIgnoreCase));
s.WithDefaultConventions();
});
}
To inject a service, you can now create Installer files for each service. Below is an example.
namespace Project.Web.Installers
{
public class ApiServiceInstaller : IInstaller
{
public void InstallServices(ServiceRegistry services, IConfiguration configuration)
{
//Load IApiService in DI
services.AddSingleton<IApiService, ApiService>();
}
}
}
This convention can be used to set up plugin services for your solution as well. I will be using this configuration for the next of my articles over .NET Core.
Please drop a comment below if you have any queries.