コード例 #1
0
 private IEnumerable <DynamicRegistration> GetX(Type serviceType, object key)
 {
     if (serviceType == typeof(X))
     {
         return new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A))) }
     }
     ;
     return(null);
 }
コード例 #2
0
ファイル: RegisterResolve.cs プロジェクト: dadhi/DryIoc
    public void Example()
    {
        var container = new Container();

        container.Register(typeof(IA), ReflectionFactory.Of(typeof(A), Reuse.Singleton));

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

        Assert.IsInstanceOf <A>(a);
    }
コード例 #3
0
        public void Can_replace_keyed_registration()
        {
            var container = new Container(rules => rules.WithDynamicRegistrations(
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                 ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A)), IfAlreadyRegistered.Replace, "a") }
                 : null,
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                    ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(B)), IfAlreadyRegistered.Replace, "a") }
                    : null));

            container.Register <X>(serviceKey: "a");

            var a = container.Resolve <X>("a");

            Assert.IsInstanceOf <B>(a);
        }
コード例 #4
0
        public void Will_keep_first_keyed_registration_by_default()
        {
            var container = new Container(rules => rules.WithDynamicRegistrations(
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                    ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A)), serviceKey: "a") }
                    : null,
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                    ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(B)), serviceKey: "a") }
                    : null));

            container.Register <X>(serviceKey: "a");

            var a = container.Resolve <X>("a");

            Assert.IsInstanceOf <X>(a);
        }
コード例 #5
0
        public void Can_replace_normal_with_dynamic_and_dynamic_with_dynamic_registration()
        {
            var container = new Container(rules => rules.WithDynamicRegistrations(
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                    ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A)), IfAlreadyRegistered.Replace) }
                    : null,
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                    ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A)), IfAlreadyRegistered.Replace) }
                    : null));

            container.Register <X, B>();

            var x = container.Resolve <X>();

            Assert.IsInstanceOf <A>(x);
        }
コード例 #6
0
ファイル: RegisterResolve.cs プロジェクト: dadhi/DryIoc
    public void Example()
    {
        // Allows registration of B which implements IDisposable as Transient, which is default `RegisterMany` reuse.
        var container = new Container(rules => rules
                                      .WithTrackingDisposableTransients());

        // Registers X, Y and A itself with A implementation
        container.RegisterMany <A>();

        // Registers only X and Y, but not A itself
        container.RegisterMany <A>(serviceTypeCondition: type => type.IsInterface);

        // X, Y, A are sharing the same singleton
        container.RegisterMany <A>(Reuse.Singleton);
        Assert.AreSame(container.Resolve <X>(), container.Resolve <Y>());

        // Registers X, Y with A and X with B
        // IDisposable is too general to be considered as a service type,
        // see the full list of excluded types after example below.
        container.RegisterMany(
            new[] { typeof(A), typeof(B) },
            serviceTypeCondition: type => type.IsInterface);

        // Registers only X with A and X with B
        container.RegisterMany(
            new[] { typeof(A), typeof(B) },
            serviceTypeCondition: type => type == typeof(X));

        // The same as above if A and B in the same assembly.
        // Plus registers the rest of the types from assembly of A.
        container.RegisterMany(new[] { typeof(A).Assembly }, type => type == typeof(X));

        // Made.Of expression is supported too
        container.RegisterMany(Made.Of(() => CreateA()));

        // Explicit about what services to register
        container.RegisterMany(new[] { typeof(X), typeof(Y) }, typeof(A));

        // Provides full control to you
        container.RegisterMany(new[] { typeof(A).Assembly },
                               getServiceTypes: implType => implType.GetImplementedServiceTypes(),
                               getImplFactory: implType => ReflectionFactory.Of(implType,
                                                                                implType.IsAssignableTo <IDisposable>() ? Reuse.Scoped : Reuse.Transient,
                                                                                FactoryMethod.ConstructorWithResolvableArguments));
    }
コード例 #7
0
        public void Resolve_mock_for_non_registered_service()
        {
            var container = new Container(rules => rules.WithUnknownServiceResolvers(request =>
            {
                var serviceType = request.ServiceType;
                if (!serviceType.IsAbstract)
                {
                    return(null); // Mock interface or abstract class only.
                }
                return(ReflectionFactory.Of(made: Made.Of(
                                                serviceReturningExpr: () => Substitute.For(Arg.Index <Type[]>(0), Arg.Index <object[]>(1)),
                                                _ => new[] { serviceType }, _ => (object[])null)));
            }));

            var sub = container.Resolve <INotImplementedService>();

            Assert.That(sub, Is.InstanceOf <INotImplementedService>());
        }
コード例 #8
0
        public void Can_validate_dynamic_registration()
        {
            var container = new Container(rules => rules.WithDynamicRegistrations(
                                              (serviceType, serviceKey) =>
            {
                if (serviceType == typeof(X))
                {
                    return new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(C))) }
                }
                ;
                return(null);
            }));

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

            Assert.AreEqual(Error.NameOf(Error.RegisteringImplementationNotAssignableToServiceType), ex.ErrorName);
        }
コード例 #9
0
        public static IContainer CreateTestContainer(IContainer container)
        {
            var c = container.CreateChild(IfAlreadyRegistered.Replace,
                                          container.Rules.WithDynamicRegistration((serviceType, serviceKey) =>
            {
                // ignore services with non-default key
                if (serviceKey != null)
                {
                    return(null);
                }

                if (serviceType == typeof(object))
                {
                    return(null);
                }

                // get the Mock object for the abstract class or interface
                if (serviceType.IsInterface || serviceType.IsAbstract)
                {
                    // except for the open-generic ones
                    if (serviceType.IsGenericType && serviceType.IsOpenGeneric())
                    {
                        return(null);
                    }

                    var mockType = typeof(Mock <>).MakeGenericType(serviceType);

                    var mockFactory = DelegateFactory.Of(r => ((Mock)r.Resolve(mockType)).Object, Reuse.Singleton);

                    return(new[] { new DynamicRegistration(mockFactory, IfAlreadyRegistered.Keep) });
                }

                // concrete types
                var concreteTypeFactory = ReflectionFactory.Of(serviceType, Reuse.Singleton,
                                                               FactoryMethod.ConstructorWithResolvableArgumentsIncludingNonPublic);

                return(new[] { new DynamicRegistration(concreteTypeFactory) });
            },
                                                                                  DynamicRegistrationFlags.Service | DynamicRegistrationFlags.AsFallback));

            c.Register(typeof(Mock <>), Reuse.Singleton, FactoryMethod.DefaultConstructor());

            return(c);
        }
コード例 #10
0
        public void Can_exclude_dynamic_registration_if_there_is_a_normal_one()
        {
            var container = new Container(rules => rules.WithDynamicRegistrations(
                                              (serviceType, serviceKey) =>
            {
                if (serviceType == typeof(X))
                {
                    return new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A)), IfAlreadyRegistered.Keep) }
                }
                ;
                return(null);
            }));

            container.Register <X, B>();

            var x = container.Resolve <X>();

            Assert.IsInstanceOf <B>(x);
        }
コード例 #11
0
        public void Can_append_new_implementation_via_dynamic_registration()
        {
            var container = new Container(rules => rules.WithDynamicRegistrations(
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                     ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A)), IfAlreadyRegistered.AppendNewImplementation) }
                     : null,
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                     ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A)), IfAlreadyRegistered.AppendNewImplementation) }
                     : null,
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                    ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(B)), IfAlreadyRegistered.AppendNewImplementation) }
                    : null));

            container.Register <X>();

            var xs = container.ResolveMany <X>().Select(x => x.GetType());

            CollectionAssert.AreEquivalent(new[] { typeof(X), typeof(A), typeof(B) }, xs);
        }
コード例 #12
0
        public void RegisterMany_can_suppress_the_exception_if_no_service_is_registered()
        {
            var c = new Container();

            c.Register <A>(Reuse.Scoped); // should be kept
            c.Register <B>(Reuse.Scoped); // should be kept too

            var implTypes = new[] { typeof(A), typeof(B) };

            c.RegisterManyIgnoreNoServicesWereRegistered(implTypes,
                                                         implType => implType
                                                         .GetRegisterManyImplementedServiceTypes(nonPublicServiceTypes: true)
                                                         .Where(st => !c.IsRegistered(st, condition: factory => factory.Reuse == Reuse.Scoped))
                                                         .ToArray(),
                                                         t => ReflectionFactory.Of(t, Reuse.Transient),
                                                         ifAlreadyRegistered: IfAlreadyRegistered.Replace);

            Assert.IsTrue(c.IsRegistered <A>(condition: f => f.Reuse == Reuse.Scoped));
            Assert.IsTrue(c.IsRegistered <B>(condition: f => f.Reuse == Reuse.Scoped));
        }
コード例 #13
0
ファイル: DryIocAdapter.cs プロジェクト: nodyang/DryIoc
        /// <summary>Unpacks the service descriptor to register the service in DryIoc container</summary>
        public static void RegisterDescriptor(this IContainer container, ServiceDescriptor descriptor)
        {
            var serviceType = descriptor.ServiceType;
            var implType    = descriptor.ImplementationType;

            if (implType != null)
            {
                container.Register(ReflectionFactory.Of(implType, descriptor.Lifetime.ToReuse()), serviceType,
                                   null, null, isStaticallyChecked: implType == serviceType);
            }
            else if (descriptor.ImplementationFactory != null)
            {
                container.Register(DelegateFactory.Of(descriptor.ImplementationFactory.ToFactoryDelegate, descriptor.Lifetime.ToReuse()), serviceType,
                                   null, null, isStaticallyChecked: true);
            }
            else
            {
                var instance = descriptor.ImplementationInstance;
                container.Register(InstanceFactory.Of(instance), serviceType,
                                   null, null, isStaticallyChecked: true);
                container.TrackDisposable(instance);
            }
        }