So there are two approaches to achieve that.
- You can use the Generic Host Builder, which is kind of the same as ASP.NET Core, as ASP.NET Core is using a specialised implementation of the builder called WebHostBuilder. As an example, your console app will look sth like that ( example copied from this post: How to run .NET Core Console app using generic host builder)
using Microsoft.Extensions.Hosting; // Requires NuGet package
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services => { services.AddTransient<MyService>(); })
.UseLamar() // now you can use this
.Build();
var my = host.Services.GetRequiredService<MyService>();``
await my.ExecuteAsync();
class MyService
{
private readonly ILogger<MyService> _logger;
public MyService(ILogger<MyService> logger)
{
_logger = logger;
}
public async Task ExecuteAsync(CancellationToken stoppingToken = default)
{
_logger.LogInformation("Doing something");
}
// and use this just like ASP.NET Core
public void ConfigureContainer(ServiceRegistry services)
{
// Supports ASP.Net Core DI abstractions
services.AddMvc();
services.AddLogging();
// Also exposes Lamar specific registrations
// and functionality
services.Scan(s =>
{
s.TheCallingAssembly();
s.WithDefaultConventions();
});
}
}
- Using a pure console app and Lamar container
using Lamar;
var container = new Container(x => { x.AddTransient<IClock, Clock>(); });
container.GetInstance<IClock>();
In this scenario, you will have to share the container and use various methods to get objects from the container. I have not tried it but I believe that you can use BuildMethod to get the object with all dependencies.
Simply you can follow this documentation: https://jasperfx.github.io/lamar/guide/ioc/bootstrapping.html#bootstrapping-a-container
on how to see tup but Scanner is similar for both scenarios.