I'm having a problem with ReuseScope.Request
. I'm getting the same instance injected on every request even though I specify ReuseScope.Request
. I configured the container using these two calls to get a MasterConfig:
this.container.RegisterAutoWiredAs<ApiConfigFactory, IConfigFactory>().ReusedWithin(ReuseScope.Container);
this.container.Register(c => c.Resolve<IConfigFactory>().GetMasterConfig(true)).ReusedWithin(ReuseScope.Request);
The GetMasterConfig(true) method returns a new concrete MasterConfig. However, when I try to use the MasterConfig in the service, I get the same instance on every request.
public class MyService
{
private readonly MasterConfig masterConfig;
public SaleService(MasterConfig masterConfig)
{
this.masterConfig = masterConfig;
}
public object Post(MyRequest request)
{
// **masterConfig is the same instance here on every request**
}
}
If I change the scope on the MasterConfig Register to ReuseScope.None
, I get a new MasterConfig loaded as expected. What am I missing? Is there a problem with the way I am registering MasterConfig? Why does ReuseScope.None
fix the issue? Why does ReuseScope.Request
give me the same instance?
Note:
I haven't been able to reproduce this in either a self-host or ASP.NET Host.
This works in the latest version of ServiceStack:
//AppHost
public class RequestScopeAppHost : AppSelfHostBase
{
public RequestScopeAppHost()
: base(typeof(RequestScopeAppHost).Name, typeof(RequestScopeService).Assembly) {}
private static int counter = 0;
public override void Configure(Container container)
{
container.Register(c => new MasterConfig {
Id = Interlocked.Increment(ref counter)
}).ReusedWithin(ReuseScope.Request);
}
}
Service:
public class MasterConfig
{
public int Id { get; set; }
}
public class GetMasterConfig : IReturn<MasterConfig> { }
public class RequestScopeService : Service
{
private readonly MasterConfig config;
public RequestScopeService(MasterConfig config)
{
this.config = config;
}
public object Any(GetMasterConfig request)
{
return config;
}
}
Test:
[TestFixture]
public class RequestScopeIssue
{
private readonly ServiceStackHost appHost;
public RequestScopeIssue()
{
appHost = new RequestScopeAppHost()
.Init()
.Start(Config.AbsoluteBaseUri);
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
appHost.Dispose();
}
[Test]
public void Can_get_RequestScope_dependency()
{
var client = new JsonServiceClient(Config.AbsoluteBaseUri);
Assert.That(client.Get(new GetMasterConfig()).Id, Is.EqualTo(1));
Assert.That(client.Get(new GetMasterConfig()).Id, Is.EqualTo(2));
Assert.That(client.Get(new GetMasterConfig()).Id, Is.EqualTo(3));
}
}
In your description ReuseScope.None
also works as intended, it doesn't re-use instances.