dadhi / DryIoc

DryIoc is fast, small, full-featured IoC Container for .NET
MIT License
1.01k stars 123 forks source link

Scoped service decorator #623

Closed alex-dubatov closed 6 months ago

alex-dubatov commented 9 months ago

DryIoc.dll 5.4.3

Have a nice day!

I have globally registered service. My goal is to use decorator for the service in scope.

I have made test method for probe. For the first time it looks working.

But if I will uncomment specified line then unexpectedly get error. Please check code below.

Maybe I don't understand something. Thank you!

 public interface ITest
 {
     int Foo();
 }

 public class GlobalService
 {
     public ITest T { get; }

     public GlobalService(ITest test) => T = test;

     public int Foo() => T.Foo();
 }

 public class TestGlobal : ITest
 {
     public int Foo() => 2;
 }

 public class TestDecoratorScoped : ITest
 {
     private readonly ITest _test;

     public TestDecoratorScoped(ITest test) => _test = test;

     public int Foo() => _test.Foo() * 3;
 }

 [Test]
 public void _issue()
 {
     var c = new Container();
     c.Register<GlobalService>(Reuse.Singleton);
     c.Register<ITest, TestGlobal>(Reuse.Transient);

     c.Register<ITest, TestDecoratorScoped>(
         reuse: Reuse.Scoped,
         setup: Setup.DecoratorWith(condition: req => req.CurrentScope != null));

     Assert.AreEqual(2, c.Resolve<GlobalService>().Foo());
     // Assert.AreEqual(2, c.Resolve<ITest>().Foo());

     var t2 = c.OpenScope().Resolve<ITest>();
     Assert.IsInstanceOf<TestDecoratorScoped>(t2); // if uncomment code above then we will get error here
     Assert.AreEqual(6, t2.Foo());
 }
dadhi commented 9 months ago

@alex-dubatov Interesting, thanks for the test - I will check.

alex-dubatov commented 7 months ago

@dadhi When the fix will be released? Very necessary.

dadhi commented 7 months ago

@alex-dubatov soonish

dadhi commented 6 months ago

@alex-dubatov The https://www.nuget.org/packages/DryIoc.dll/6.0.0-preview-07 is released. So you may try it out.