Skip to content

HostSyringe

NexusLabs.Needlr.Hosting

HostSyringe Class

Provides a fluent API for configuring and building host applications using Needlr. Wraps a ConfiguredSyringe with additional host functionality.

public sealed record HostSyringe : System.IEquatable<NexusLabs.Needlr.Hosting.HostSyringe>

Inheritance System.Object 🡒 HostSyringe

Implements System.IEquatable<HostSyringe>

Example

Creating and configuring a HostSyringe:

// Transition from ConfiguredSyringe
var hostSyringe = new Syringe()
    .UsingReflection()
    .ForHost();

// Build and run the host
var host = hostSyringe
    .UsingOptions(() => CreateHostOptions.Default.UsingArgs(args))
    .UsingConfigurationCallback((builder, options) => 
    {
        // Configure the HostApplicationBuilder
        builder.Configuration.AddJsonFile("custom-settings.json", optional: true);
        builder.Services.AddSingleton<IMyCustomService, MyCustomService>();
    })
    .BuildHost();

await host.RunAsync();

Constructors

HostSyringe(ConfiguredSyringe) Constructor

Initializes a new instance of the HostSyringe class.

public HostSyringe(NexusLabs.Needlr.Injection.ConfiguredSyringe baseSyringe);

Parameters

baseSyringe NexusLabs.Needlr.Injection.ConfiguredSyringe

The configured syringe to wrap.

Example

var configuredSyringe = new Syringe().UsingReflection();

var hostSyringe = new HostSyringe(configuredSyringe);

Methods

HostSyringe.BuildHost() Method

Builds a host with the configured settings.

public Microsoft.Extensions.Hosting.IHost BuildHost();

Returns

Microsoft.Extensions.Hosting.IHost
The configured Microsoft.Extensions.Hosting.IHost.

Example

var host = new Syringe()
    .UsingReflection()
    .UsingScrutorTypeRegistrar()
    .ForHost()
    .UsingOptions(() => CreateHostOptions.Default
        .UsingArgs(args)
        .UsingApplicationName("My Worker Service"))
    .UsingConfigurationCallback((builder, options) =>
    {
        // Add custom configuration sources
        builder.Configuration.AddJsonFile("appsettings.local.json", optional: true);

        // Register additional services
        builder.Services.AddSingleton<ICustomService, CustomService>();
    })
    .BuildHost();

await host.RunAsync();

HostSyringe.BuildServiceProvider(IConfiguration) Method

Builds a service provider with the configured settings.

public System.IServiceProvider BuildServiceProvider(Microsoft.Extensions.Configuration.IConfiguration config);

Parameters

config Microsoft.Extensions.Configuration.IConfiguration

The configuration to use for building the service provider.

Returns

System.IServiceProvider
The configured System.IServiceProvider.

Example

var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

var serviceProvider = new Syringe()
    .UsingReflection()
    .UsingScrutorTypeRegistrar()
    .ForHost()
    .BuildServiceProvider(config);

var myService = serviceProvider.GetRequiredService<IMyService>();