Ejemplo n.º 1
0
        public void Resolve_service_reused_in_resolution_scope_succeed_if_key_matched()
        {
            var container = new Container();

            container.Register <AccountUser>(made: Parameters.Of.Type <Account>(serviceKey: "account"));
            container.Register <Account>(serviceKey: "account", setup: Setup.With(openResolutionScope: true));
            container.Register <Log>(Reuse.ScopedTo(serviceKey: "account"));

            var user = container.Resolve <AccountUser>();

            Assert.IsNotNull(user.Account.Log);
        }
Ejemplo n.º 2
0
        public void Sample_based_registration_condition_and_resolution_scope()
        {
            var c = new Container();

            // register tenants with respective key + plus instruct tenant to open its scope
            c.Register <ITenant, GreenTenant>(serviceKey: TenantKey.Green, setup: Setup.With(openResolutionScope: true));
            c.Register <ITenant, BlueTenant>(serviceKey: TenantKey.Blue, setup: Setup.With(openResolutionScope: true));

            // green tenant services
            var greenSetup = Setup.With(condition: req => IsTenant(req, TenantKey.Green), asResolutionCall: true);

            c.Register <ITransient, GreenTransient>(setup: greenSetup);
            c.Register <IScoped, GreenScoped>(Reuse.Scoped, setup: greenSetup);
            c.Register <ISingleton, GreenSingleton>(Reuse.ScopedTo <ITenant>(TenantKey.Green));

            // default services
            c.Register <ISomeController, SomeController>(Reuse.Scoped);
            c.Register <ITransient, DefaultTransient>();
            c.Register <IScoped, DefaultScoped>(Reuse.Scoped);
            c.Register <ISingleton, DefaultSingleton>(Reuse.Singleton);

            using (var reqScope = c.OpenScope())
            {
                var tenants = new[]
                {
                    GetAndAssertTenantServices(reqScope, TenantKey.Green, "Green"),
                    GetAndAssertTenantServices(reqScope, TenantKey.Blue, "Default")
                };

                // cross tenant resolution
                var transients = tenants.Select(t => t.Resolver.Resolve <ITransient>().GetType()).ToArray();
                CollectionAssert.AreEquivalent(new[] { typeof(GreenTransient), typeof(DefaultTransient) }, transients);
            }

            using (var reqScope = c.OpenScope())
            {
                var tenants = new[]
                {
                    GetAndAssertTenantServices(reqScope, TenantKey.Green, "Green"),
                    GetAndAssertTenantServices(reqScope, TenantKey.Blue, "Default")
                };

                // cross tenant resolution
                var transients = tenants.Select(t => t.Resolver.Resolve <ITransient>().GetType()).ToArray();
                CollectionAssert.AreEquivalent(new[] { typeof(GreenTransient), typeof(DefaultTransient) }, transients);
            }

            var allTransients = c.ResolveMany <ITransient>();

            // will be 1 default, because tenant transients can be resolved only through a tenant
            Assert.AreEqual(1, allTransients.Count());
        }
Ejemplo n.º 3
0
        public void Resolution_scope_should_be_propagated_through_resolution_call_intermediate_dependencies()
        {
            var container = new Container();

            container.Register <AD>(Reuse.ScopedTo <AResolutionScoped>());
            container.Register <ADConsumer>(setup: Setup.With(asResolutionCall: true));
            container.Register <AResolutionScoped>(setup: Setup.With(openResolutionScope: true));

            var scoped = container.Resolve <AResolutionScoped>();

            Assert.IsNotNull(scoped);
            Assert.AreSame(scoped.Consumer.Ad, scoped.Consumer.Ad2);
        }
Ejemplo n.º 4
0
        public void Resolve_can_resolve_decorator_as_resolution_call_together_with_resolution_scope_reuse()
        {
            var container = new Container();

            container.Register <B>(Reuse.ScopedTo <IA>());
            container.Register <IA, A>();
            container.Register <IA, D>(setup: Setup.DecoratorWith(_ => true, openResolutionScope: true));

            var a = container.Resolve(typeof(IA));

            Assert.IsInstanceOf <D>(a);
            Assert.AreSame(((D)a).B, ((D)a).Bb);
        }
Ejemplo n.º 5
0
        public void ResolveMany_can_resolve_decorator_with_dependency()
        {
            var container = new Container();

            container.Register <B>(Reuse.ScopedTo <IA>());
            container.Register <IA, A>();
            container.Register <IA, D>(setup: Setup.DecoratorWith(_ => true, openResolutionScope: true));

            var a = container.ResolveMany(typeof(IA)).First();

            Assert.IsInstanceOf <D>(a);
            Assert.AreSame(((D)a).B, ((D)a).Bb);
        }
Ejemplo n.º 6
0
    [Test] public void Example()
    {
        var container = new Container();

        container.Register <Foo>(setup: Setup.With(openResolutionScope: true));

        container.Register <Dependency>(Reuse.ScopedTo <Foo>());

        var foo = container.Resolve <Foo>();

        container.Dispose();
        Assert.IsTrue(foo.Dep.IsDisposed);
    }
        public void Test()
        {
            var container = new Container();

            container.RegisterMany <Layr1>(Reuse.ScopedTo <IComp>(), nonPublicServiceTypes: true);
            container.RegisterMany <Layr2>(Reuse.ScopedTo <IComp>(), nonPublicServiceTypes: true);
            container.RegisterMany <Comp1>(Reuse.Singleton, nonPublicServiceTypes: true, setup: Setup.With(openResolutionScope: true));
            container.RegisterMany <Comp2>(Reuse.Singleton, nonPublicServiceTypes: true, setup: Setup.With(openResolutionScope: true));
            container.RegisterMany <Serv1>(Reuse.Singleton, nonPublicServiceTypes: true);
            container.RegisterMany <Serv2>(Reuse.Singleton, nonPublicServiceTypes: true);

            container.Resolve <Serv1>();
        }
Ejemplo n.º 8
0
    [Test] public void Example()
    {
        var container = new Container();

        // `openResolutionScope` option is required to open the scope for the `Foo`
        container.Register <Foo>(setup: Setup.With(openResolutionScope: true));

        container.Register <Dependency>();
        container.Register <SubDependency>(Reuse.ScopedTo <Foo>());

        var foo = container.Resolve <Foo>();

        Assert.AreSame(foo.Sub, foo.Dep.Sub);
    }
Ejemplo n.º 9
0
    public void Example()
    {
        var container = new Container();

        container.Register <I, A>(Reuse.ScopedTo("a"));
        container.Register <I, B>(Reuse.ScopedTo("b"));

        using (var scope = container.OpenScope("b"))
        {
            // will skip a registration of `A` because the open scope has different name
            var b = scope.Resolve <I>();
            Assert.IsInstanceOf <B>(b);
        }
    }
Ejemplo n.º 10
0
    public void Example()
    {
        var container = new Container(rules => rules
                                      .WithoutImplicitCheckForReuseMatchingScope());

        container.Register <I, A>(Reuse.ScopedTo("a"));
        container.Register <I, B>(Reuse.ScopedTo("b"));

        using (var scope = container.OpenScope("b"))
        {
            // Throws an exception because of the multiple `I` registrations found
            Assert.Throws <ContainerException>(() => scope.Resolve <I>());
        }
    }
        public void Test()
        {
            var c = new Container(r => r
                                  .WithoutThrowOnRegisteringDisposableTransient()
                                  .With(FactoryMethod.ConstructorWithResolvableArguments));

            c.RegisterMany(new[] {
                typeof(IMediator).GetAssembly(),
                typeof(SomeRequestHandler).GetAssembly()
            },
                           type => type.GetTypeInfo().IsInterface
                           // exclude action handler so we can register by key
                           && !typeof(IActionHandler).IsAssignableFrom(type));

            c.RegisterDelegate <SingleInstanceFactory>(r => serviceType => r.Resolve(serviceType));
            c.RegisterDelegate <MultiInstanceFactory>(r => serviceType => r.ResolveMany(serviceType));

            c.Register <IActionHandler, SomeActionHandler>(serviceKey: "key1");
            c.Register <IActionHandler, SomeActionHandler2>(serviceKey: "key2");
            c.Register <IActionHandler, SomeActionHandler3>(serviceKey: "key3");
            c.Register <IActionHandler, SomeActionHandler4>(serviceKey: "key4");

            c.Register(typeof(IAsyncRequestHandler <,>), typeof(Decorator <,>),
                       made: Parameters.Of.Type <IActionHandler>(serviceKey: "key1"),
                       setup: Setup.DecoratorWith(r => true, openResolutionScope: true));

            c.Register(typeof(IAsyncRequestHandler <,>), typeof(Decorator <,>),
                       made: Parameters.Of.Type <IActionHandler>(serviceKey: "key2"),
                       setup: Setup.DecoratorWith(r => true, openResolutionScope: true));

            c.Register(typeof(IAsyncRequestHandler <,>), typeof(Decorator <,>),
                       made: Parameters.Of.Type <IActionHandler>(serviceKey: "key3"),
                       setup: Setup.DecoratorWith(r => true, openResolutionScope: true));

            c.Register(typeof(IAsyncRequestHandler <,>), typeof(Decorator <,>),
                       made: Parameters.Of.Type <IActionHandler>(serviceKey: "key4"),
                       setup: Setup.DecoratorWith(r => true, openResolutionScope: true));

            c.Register <Command1>();
            c.Register <CommandFactory>();

            c.Register <DbContext, Model1>(Reuse.ScopedTo(typeof(IAsyncRequestHandler <,>)));
            c.Register <DbContext, Model1>(Reuse.ScopedTo(typeof(IAsyncNotificationHandler <>)));

            var mediator = c.Resolve <IMediator>();

            var x = mediator.SendAsync(new RequestCommand()).Result;

            Assert.AreEqual("success", x);
        }
Ejemplo n.º 12
0
    public void Example()
    {
        var container = new Container();

        // This is required to mark that `Foo` opens the scope
        container.Register <Foo>(setup: Setup.With(openResolutionScope: true));

        container.Register <Dependency>(Reuse.ScopedTo <Foo>());

        var foo = container.Resolve <Foo>();

        container.Dispose();
        Assert.IsTrue(foo.Dep.IsDisposed);
    }
        public void Test_with_default_container_rules()
        {
            var container = new Container();

            container.Register <TestScope1>(setup: Setup.With(openResolutionScope: true));
            container.Register <TestScope2>(setup: Setup.With(openResolutionScope: true));
            container.Register <Test1>(Reuse.ScopedTo <TestScope1>());
            container.Register <Test1>(Reuse.ScopedTo <TestScope2>());

            var t1 = container.Resolve <TestScope1>();
            var t2 = container.Resolve <TestScope2>();

            Assert.AreNotSame(t1.Test1, t2.Test1);
        }
Ejemplo n.º 14
0
        public void Scoped_service_can_open_resolution_scope()
        {
            var container = new Container();

            container.Register <O>(Reuse.Scoped, setup: Setup.With(openResolutionScope: true));
            container.Register <Ho>(Reuse.ScopedTo <O>());

            using (var scope = container.OpenScope())
            {
                var o  = scope.Resolve <O>();
                var o2 = scope.Resolve <O>();
                Assert.AreNotSame(o, o2);
                Assert.AreSame(o.Ho, o.Ho2);
            }
        }
Ejemplo n.º 15
0
        public void Can_control_disposing_of_matching_resolution_scope_with_wrapper()
        {
            var container = new Container();

            container.Register <AccountUser>();
            container.Register <Account, CarefulAccount>(Reuse.Singleton, setup: Setup.With(openResolutionScope: true));
            container.Register <Log, DisposableLog>(Reuse.ScopedTo <Account>());

            var user = container.Resolve <AccountUser>();

            Assert.IsNotNull(user.Account.Log);
            ((IDisposable)user.Account).Dispose();

            Assert.IsTrue(((DisposableLog)user.Account.Log).IsDisposed);
        }
        public void Test_with_MS_DI_container_rules()
        {
            var container = new Container(rules => rules
                                          .WithFactorySelector(Rules.SelectLastRegisteredFactory()));

            container.Register <TestScope1>(setup: Setup.With(openResolutionScope: true));
            container.Register <TestScope2>(setup: Setup.With(openResolutionScope: true));
            container.Register <Test1>(Reuse.ScopedTo <TestScope1>());
            container.Register <Test1>(Reuse.ScopedTo <TestScope2>());

            var t1 = container.Resolve <TestScope1>();
            var t2 = container.Resolve <TestScope2>();

            Assert.AreNotSame(t1.Test1, t2.Test1);
        }
Ejemplo n.º 17
0
        public void If_not_fully_matched_resolution_scope_found_Then_the_top_scope_will_be_used()
        {
            var container = new Container();

            container.Register <AccountUser>();
            container.Register <Account>(setup: Setup.With(openResolutionScope: true));
            container.Register <Log>(Reuse.ScopedTo <Account>("account"));

            var ex = Assert.Throws <ContainerException>(() =>
                                                        container.Resolve <AccountUser>());

            Assert.AreEqual(
                Error.NameOf(Error.NoMatchedScopeFound),
                Error.NameOf(ex.Error));
        }
Ejemplo n.º 18
0
    [Test] public void Example()
    {
        var container = new Container(rules => rules
                                      .WithTrackingDisposableTransients() // we need this to allow disposable transient Foo
                                      );

        container.Register <Foo>(setup: Setup.With(openResolutionScope: true));

        container.Register <Dependency>(Reuse.ScopedTo <Foo>());

        var foo = container.Resolve <Foo>();

        // Disposing the foo will dispose its scope and the scoped dependencies down the tree
        foo.Dispose();

        Assert.IsTrue(foo.Dep.IsDisposed);
    }
Ejemplo n.º 19
0
        public void Test_with_Validate()
        {
            using (var container = new Container())
            {
                var outerScoped = Reuse.ScopedTo("Outer");
                container.Register <SomethingDefinedInOuterScope>(outerScoped);

                var innerScoped = Reuse.ScopedTo("Inner", false, outerScoped.Lifespan - 1);
                container.Register <SomethingDefinedInInnerScope>(innerScoped);

                var errors = container.Validate();
                Assert.AreEqual(1, errors.Length);
                Assert.AreEqual(
                    Error.NameOf(Error.DependencyHasShorterReuseLifespan),
                    errors[0].Value.ErrorName);
            }
        }
        public void Test()
        {
            var container = new Container();

            container.Register <IDep, Dep1>(Reuse.ScopedTo <Owner1>());
            container.Register <IDep, Dep2>(Reuse.ScopedTo <Owner2>());

            container.RegisterMany <Owner1>(Reuse.Singleton, setup: Setup.With(openResolutionScope: true));
            container.RegisterMany <Owner2>(Reuse.Singleton, setup: Setup.With(openResolutionScope: true));

            var owner1 = container.Resolve <Owner1>();
            var owner2 = container.Resolve <Owner2>();

            Assert.AreNotSame(owner1.Dep, owner2.Dep);
            Assert.IsInstanceOf <Dep1>(owner1.Dep);
            Assert.IsInstanceOf <Dep2>(owner2.Dep);
        }
Ejemplo n.º 21
0
        public void Test()
        {
            using (var container = new Container())
            {
                container.Register <SomethingDefinedInOuterScope>(Reuse.ScopedTo("Outer"));
                container.Register <SomethingDefinedInInnerScope>(Reuse.ScopedTo("Inner"));
                container.Validate();

                using (var outerScopedContainer = container.OpenScope("Outer"))
                {
                    using (var innerScopedContainer = outerScopedContainer.OpenScope("Inner"))
                    {
                        var item = innerScopedContainer.Resolve <SomethingDefinedInOuterScope>();
                        Assert.IsNotNull(item);
                    }
                }
            }
        }
Ejemplo n.º 22
0
        public void Minimal_test()
        {
            var container = new Container();

            container.Register <Aa>(setup: Setup.With(openResolutionScope: true));
            container.Register <Bb>(setup: Setup.With(openResolutionScope: true));
            container.Register <Dd>();
            container.Register <IXx, Xx>(Reuse.ScopedTo <Aa>());
            container.Register <IXx, Yy>(Reuse.ScopedTo <Bb>());

            var a = container.Resolve <Aa>();

            Assert.IsInstanceOf <Xx>(a.D.Xx);

            var b = container.Resolve <Bb>();

            Assert.IsInstanceOf <Yy>(b.D.Xx);
        }
Ejemplo n.º 23
0
        public void Test_using_open_scope()
        {
            var c = new Container();

            using (var parent = c.OpenScope("parent"))
            {
                c.Register(typeof(IFruit), typeof(Melon), Reuse.ScopedTo("parent"));

                using (var child = parent.OpenScope())
                {
                    c.Register(typeof(IJuice), typeof(FruitJuice));

                    var parentFruit = parent.Resolve <IFruit>();
                    var snd         = child.Resolve <IJuice>();

                    Assert.That(parentFruit, Is.SameAs(snd.Fruit));
                }
            }
        }
Ejemplo n.º 24
0
    public void Example()
    {
        var container = new Container();

        container.Register <Car>(Reuse.ScopedTo("top"));

        using (var s1 = container.OpenScope("top"))
        {
            var car1 = s1.Resolve <Car>();

            using (var s2 = s1.OpenScope())
            {
                var car2 = s2.Resolve <Car>();

                // Cars are the same despite that `car2` is resolved from the nested `s2`,
                // because it was specifically resolved from the matching name scope `s1`
                Assert.AreSame(car2, car1);
            }
        }
    }
Ejemplo n.º 25
0
        public void Given_Thread_reuse_Services_resolved_in_same_thread_should_be_the_same_In_nested_scope_too()
        {
            var container = new Container(scopeContext: new ThreadScopeContext());

            using (var scope = container.OpenScope("root"))
            {
                container.Register <Service>(Reuse.ScopedTo("root"));

                var one = scope.Resolve <Service>();

                using (var nested = scope.OpenScope())
                {
                    var two = nested.Resolve <Service>();
                    Assert.AreSame(one, two);
                }

                var another = container.Resolve <Service>();
                Assert.AreSame(one, another);
            }
        }
Ejemplo n.º 26
0
        public void TheBug_simplified_without_MS_DI_rules()
        {
            var container = new Container(rules => rules
                                          // .WithMicrosoftDependencyInjectionRules()
                                          .WithFuncAndLazyWithoutRegistration());

            container.Register <S, S1>(Reuse.ScopedTo("FirstScope"));
            container.Register <S, S2>(Reuse.ScopedTo("SecondScope"));

            using (var scope1 = container.OpenScope("FirstScope"))
            {
                var a = scope1.Resolve <S>();
                Assert.IsInstanceOf <S1>(a);
            }

            using (var scope2 = container.OpenScope("SecondScope"))
            {
                var a = scope2.Resolve <S>();
                Assert.IsInstanceOf <S2>(a);
            }
        }
    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);
        }
    }
Ejemplo n.º 28
0
        public void Test_without_Validate()
        {
            using (var container = new Container())
            {
                var outerScoped = Reuse.ScopedTo("Outer");
                container.Register <SomethingDefinedInOuterScope>(outerScoped);

                var innerScoped = Reuse.ScopedTo("Inner", false, outerScoped.Lifespan - 1);
                container.Register <SomethingDefinedInInnerScope>(innerScoped);
                //container.Validate();

                using (var outerScopedContainer = container.OpenScope(outerScoped.Name))
                {
                    using (var innerScopedContainer = outerScopedContainer.OpenScope(innerScoped.Name))
                    {
                        var ex = Assert.Throws <ContainerException>(() =>
                                                                    innerScopedContainer.Resolve <SomethingDefinedInOuterScope>());
                        Assert.AreEqual(Error.NameOf(Error.DependencyHasShorterReuseLifespan), ex.ErrorName);
                    }
                }
            }
        }
Ejemplo n.º 29
0
        public void Can_specify_multiple_scope_names_in_one_reuse()
        {
            var c = new Container();

            c.Register <Go>(Reuse.ScopedTo("a", "b"));

            using (var a = c.OpenScope("a"))
            {
                var goA = a.Resolve <Go>();
                using (var noname = a.OpenScope())
                {
                    var goNN = noname.Resolve <Go>();
                    Assert.AreSame(goNN, goA);

                    using (var b = noname.OpenScope("b"))
                    {
                        var goB = b.Resolve <Go>();
                        Assert.AreNotSame(goB, goA); // different name
                        Assert.AreSame(goB, b.Resolve <Go>());
                    }
                }
            }
        }
Ejemplo n.º 30
0
 /// <summary>Reuse.ScopeTo(name)</summary>
 public static RegistrationInfo InstancePerMatchingLifetimeScope(this RegistrationInfo info, object scopeName) => info.WithReuse(Reuse.ScopedTo(scopeName));