Fork me on GitHub

Lamar 2.0.0


Next

Registration

Previous

Bootstrapping a Container

Integration with ASP.Net Core


To use Lamar within ASP.Net Core applications, also install the Lamar.Microsoft.DependencyInjection library from Nuget to your ASP.Net Core project (and you can thank Microsoft for the clumsy naming convention, thank you).

With that Nuget installed, your normal ASP.Net Core bootstrapping changes just slightly. When you bootstrap your IWebHostBuilder object that configures ASP.Net Core, you also need to call the UseLamar() method as shown below:


public static void Main(string[] args)
{
    var builder = new WebHostBuilder();
    builder
        // Replaces the built in DI container
        // with Lamar
        .UseLamar()
        
        // Normal ASP.Net Core bootstrapping
        .UseUrls("http://localhost:5002")
        .UseKestrel()
        .UseStartup<Startup>();

    builder.Start();

}

Note! The Startup.ConfigureServices(ServiceRegistry) convention does not work as of ASP.Net Core 2.1. Use ConfigureContainer(ServiceRegistry) instead.

If you use a StartUp class for extra configuration, your ConfigureContainer() method can take in a ServiceRegistry object from Lamar for service registrations in place of the ASP.Net Core IServiceCollection interface as shown below:


public class Startup
{
    // Take in Lamar's ServiceRegistry instead of IServiceCollection
    // as your argument, but fear not, it implements IServiceCollection
    // as well
    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();
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseMvc();
    }
}

You can also still write ConfigureServices(IServiceCollection), but you'd miss out on most of Lamar's extra functionality beyond what that abstraction provides.

And that is that, you're ready to run your ASP.Net Core application with Lamar handling service resolution and object cleanup during your HTTP requests.