I'm using DryIoc in a WebApi project. The default reuse is set to Reuse.InWebRequest. In some cases I need to resolve new instances during a request. When using Reuse.InCurrentScope I can resolve new instances like so:
public class Foo : IFoo
{
public Foo(IMyDependency dep, IContainer container){
using (var scope = container.OpenScope()) {
var newInstance = scope.Resolve<IMyDependency>();
Assert.IsFalse(ReferenceEquals(dep, newInstance));
}
}
}
But when using Request.InWebRequest or Request.InThread (which are basically the same according to the documentation) no new instances are created, but already resolved instances are reused. I also tried to use IContainer.CreateFacade()
but the result is the same.
I'm wondering if there is a way to force the creation of new instances (regardless of the specified reuse) without creating a new container from scratch.
I cannot use Reuse.Transient, because I need the same instance during the request 99% of the time. I need a new instance only when abusing the container as a service locator.
You may register service twice, one with scoped and another one with transient reuse. For the transient one specify a serviceKey
when registering, and use it in service locator to identify the transient service.