Access net core container with mq workers created with Host.CreateDefaultBuilder

hi,
for mq workers, i’m typically using Host.CreateDefaultBuilder.

In my mq-worker-services, i need to access dependencies from the NetCore Container.

Is there a way to achieve this? I’ve tried it with NetCoreContainerAdapter but i didnt understand how to hook it up.

ServiceStack’s IOC can be configured to use ASP .NET Core’s IOC with:

appHost.Container.Adapter = new NetCoreContainerAdapter(app.ApplicationServices);

For IHost App’s created with Host.CreateDefaultBuilder() the services collection is available at app.Services, so you should be able to configure it with:

var app = CreateHostBuilder(args).Build();
HostContext.Container.Adapter = new NetCoreContainerAdapter(app.Services);
app.Run();
1 Like

oh nice thank you!

i’ve tried with ConfigureContainer, but it’s a chicken-egg problem there.

thank you for the solution! maybe add this to the mqworker starter template as a comment.

I’ve updated all worker project templates to use a new UserServiceStack() extension method so it’s more familiar with Web Application projects where it configures the AppHost to use .NET Core’s IOC and Logging us allows us to add more integrations in future versions without needing to change existing code:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args)
            .Build()
            .UseServiceStack(new GenericAppHost(typeof(MyService).Assembly)
            {
                ConfigureAppHost = host =>
                {
                    var mqServer = host.Resolve<IMessageService>();
                    mqServer.RegisterHandler<Hello>(host.ExecuteMessage);
                }
            })
            .Run();
    }

    static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddSingleton<IRedisClientsManager>(
                    new RedisManagerPool(hostContext.Configuration.GetConnectionString("RedisMq")));
                services.AddSingleton<IMessageService>(c => new RedisMqServer(c.Resolve<IRedisClientsManager>()) {
                    DisablePublishingToOutq = true,
                });
                services.AddHostedService<MqWorker>();
            });
}

This change is available from v6.10.1+ that’s now available in our Pre Release packages.