I am using Autofac version 3.5.2.
I want to register a singleton class A that needs B until some point in the future. How do you do this if B is registered using InstancePerRequest?
Using Owned<B> directly does not work because the per request lifetime scope does not exist. You get the DependencyResolutionException as seen here.
One solution is to make A have a direct dependency on ILifetimeScope. A begins a scope with the MatchingScopeLifetimeTags.RequestLifetimeScopeTag when it needs an instance of B.
using (var scope = this.lifetimeScope.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var b = scope.Resolve<B>();
b.DoSomething();
}
I do not like this approach since it is the service locator pattern. See this fiddle.
A second solution is to register B as InstancePerRequest and in the correct owned scope for B. Registering B would look like this: builder.RegisterType<B>().InstancePerRequest(new TypedService(typeof(B)));
The full example is here.
I like the second solution better but it also has problems:
It feels like a code smell that when registering B’s dependencies that they have to know to register themselves in B’s owned scope.
It does not scale well when B has a lot of dependencies and those dependencies have dependencies etc. All these dependencies need the extra registration as in problem 1 above.
How would you recommend solving this problem? Thanks for the help.
Update
I have moved the OwnedPerRequest<T> related code into this answer below.