Different Ioc behaviour on Test app host using dotnet ioc

Hi :slight_smile: ,
on an existing big app we are moving to SS 8 and dotnet 8.
We are now registering our dependencies on the IServiceCollection using the AddScoped.
While on a simple app we tried that at runtime AddScoped resolve new instances of dependencies per request which is ok, on a integration test, instead the same instance is resolved.
Here a minimal sample, the id on each request should be different but is not.

using Funq;
using ServiceStack;
using NUnit.Framework; 
using Microsoft.Extensions.DependencyInjection;

namespace IocTests2.Tests;

public class RequestNewIdResponse {
    public string Result { get; set; }}
public class RequestNewId : IReturn<RequestNewIdResponse>, IGet {}
public class MyServices(MyDependency d) : Service
{
    public object Any(RequestNewId request)
    {
        return new RequestNewIdResponse { Result = d.GetId() };
    }
}

public class MyDependency
{
    private readonly string _id;

    public MyDependency()
    {
        _id = Guid.NewGuid().ToString();
    }
    
    public string GetId() => _id;
}
public class IntegrationTest
{
    const string BaseUri = "http://localhost:2000/";
    private readonly ServiceStackHost appHost;

    class AppHost : AppSelfHostBase
    {
        public AppHost() : base(nameof(IntegrationTest), typeof(MyServices).Assembly) { }

        public override void Configure(IServiceCollection services)
        {
            services.AddScoped<MyDependency>();
        }

        public override void Configure(Container container)
        {
        }
    }

    public IntegrationTest()
    {
        appHost = new AppHost()
            .Init()
            .Start(BaseUri);
    }

    [OneTimeTearDown]
    public void OneTimeTearDown() => appHost.Dispose();

    public IServiceClient CreateClient() => new JsonServiceClient(BaseUri);

    [Test]
    public void Get_DifferentId_OnEach_Call()
    {
        var client = CreateClient();

        var response = client.Get(new RequestNewId());
        var response2 = client.Get(new RequestNewId());

        Assert.That(response.Result, Is.Not.EqualTo(response2.Result));
    }
}

It’s because ServiceStack Services in AppSelfHostBase are registered when the ServiceStack AppHost is initilaized which happens after ASP .NET Core’s IOC is built so they’re only registered in ServiceStack’s IOC and are not resolvable from ASP .NET Core’s IOC which is required for scoped dependencies.

If you want different instances to be resolved, register dependencies as transient, alternatively you can register your ServiceStack Services in ASP .NET Core’s IOC’s with:

services.AddTransient<MyServices>();
services.AddScoped<MyDependency>();

Where since it exists the Service will be resolved from ASP .NET Core’s IOC.