diff --git a/src/Lamar.Testing/Bugs/Bug_385_ServiceScopeFactory_is_not_root.cs b/src/Lamar.Testing/Bugs/Bug_385_ServiceScopeFactory_is_not_root.cs new file mode 100644 index 00000000..b0d792b5 --- /dev/null +++ b/src/Lamar.Testing/Bugs/Bug_385_ServiceScopeFactory_is_not_root.cs @@ -0,0 +1,33 @@ +namespace Lamar.Testing.Bugs; + +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; + +public class Bug_385_ServiceScopeFactory_is_not_root +{ + [Fact] + public void Test() + { + var container = Container.For(x => + { + x.Use(); + }); + + var serviceScopeFactory = container.GetInstance(); + using var scope = serviceScopeFactory.CreateScope(); + var testService = scope.ServiceProvider.GetRequiredService(); + + testService.ServiceScopeFactory.ShouldBe(serviceScopeFactory); + } + + public class TestService + { + public IServiceScopeFactory ServiceScopeFactory { get; } + + public TestService(IServiceScopeFactory serviceScopeFactory) + { + ServiceScopeFactory = serviceScopeFactory; + } + } +} \ No newline at end of file diff --git a/src/Lamar/IoC/Resolvers/ScopeInstance.cs b/src/Lamar/IoC/Resolvers/ScopeInstance.cs index f50942ec..23705e23 100644 --- a/src/Lamar/IoC/Resolvers/ScopeInstance.cs +++ b/src/Lamar/IoC/Resolvers/ScopeInstance.cs @@ -54,8 +54,12 @@ public CastRootScopeFrame(Type interfaceType) public void WriteExpressions(LambdaDefinition definition) { var variableExpr = definition.RegisterExpression(Variable); - definition.Body.Add(Expression.Assign(variableExpr, - Expression.Convert(definition.ExpressionFor(_scope), Variable.VariableType))); + + var root = Expression.Property(definition.ExpressionFor(_scope), nameof(Scope.Root)); + var convert = Expression.Convert(root, Variable.VariableType); + var assign = Expression.Assign(variableExpr, convert); + + definition.Body.Add(assign); } public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)