2

I would like to register two services, A & B, with different lifetimes.

My use case is simmilar to "Browser" and "Tabs".
I have one scope over the executable lifetime (browser) and one "subScope" for each tab.
I want A to be a singleton in the browser scope (browser lifetime).
Now i would like to resolve a different B, but the same A in every tab.
I've read the GitHub docs, but it looks like I would get a new A in every tab.

Pseudo-code would look like this:

var container = new Container();
container.Register<A>(Reuse.Scoped);
container.Register<B>(Reuse.Scoped);


using (var browserScope = container.OpenScope())
{
    using (var tabScope1 = browserScope.OpenScope())
    {
        var a1 = tabScope1.Resolve<A>();
        var b1 = tabScope1.Resolve<B>();
    }

    using (var tabScope2 = browserScope.OpenScope())
    {
        var a2 = tabScope2.Resolve<A>();
        var b2 = tabScope2.Resolve<B>();
    }
}

I would like a1 and a2 to be resolved as the same instance.
How can i accomplish this?

Nefarion
  • 872
  • 2
  • 8
  • 28

1 Answers1

2

You may achieve it with the named scoped like this - live example https://dotnetfiddle.net/pqZ4ah

The full source:

using System;
using DryIoc;

public class Program
{
    class A { }
    class B { }

    enum UIScope { Browser, Tab }

    public static void Main()
    {
        var container = new Container(r => r.WithUseInterpretation());
        container.Register<A>(Reuse.ScopedTo(UIScope.Browser));
        container.Register<B>(Reuse.ScopedTo(UIScope.Tab));

        using (var browserScope = container.OpenScope(UIScope.Browser))
        {
            A a1, a2;
            using (var tabScope1 = browserScope.OpenScope(UIScope.Tab))
            {
                a1 = tabScope1.Resolve<A>();
                var b1 = tabScope1.Resolve<B>();
            }

            using (var tabScope2 = browserScope.OpenScope(UIScope.Tab))
            {
                a2 = tabScope2.Resolve<A>();
                var b2 = tabScope2.Resolve<B>();
            }

            Console.WriteLine(a1 == a2);
        }
    }
}

canton7
  • 37,633
  • 3
  • 64
  • 77
dadhi
  • 4,807
  • 19
  • 25
  • Great, thanks! What are the benefits of using WithUseInterpretation? I read up on it, and i save time on program startup? Do i loose time during runtime though? – Nefarion Feb 07 '20 at 11:03
  • I've added WithUseInterpretation here because dotnetfiddle has the problem with the Reflection.Emit. – dadhi Feb 15 '20 at 14:28
  • 2
    ... `WithUseInterpretation` is 10x slower than compiled delegates but incures 100x cost for the compilation when you resolving something for the 2nd time - the 1st time is always using interretation. – dadhi Feb 15 '20 at 14:30