public void TestNoPoliciesReturnsNull()
		{
			PolicyList policies = new PolicyList();
			BuilderContext context = new BuilderContext(null, null, policies);

			Assert.IsNull(context.Policies.Get<IBuilderPolicy>(typeof (object), null));
		}
        private static MockBuilderContext BuildContext(PolicyList innerPolicies)
        {
            MockBuilderContext ctx = new MockBuilderContext(new BuildPlanStrategy());

            ctx.Policies.SetDefault<IPlanBuilderPolicy>(CreatePlanBuilder(innerPolicies));

            return ctx;
        }
예제 #3
0
        public void CanAddPolicyToBagAndRetrieveIt()
        {
            PolicyList list = new PolicyList();

            list.Set<IBuilderPolicy>(new MockPolicy(), typeof(object), null);

            Assert.IsNotNull(list.Get<IBuilderPolicy>(typeof(object), null));
        }
        private static IPlanBuilderPolicy CreatePlanBuilder(MockReturnExistingPlanBuilderStrategy mockPlanBuilderStrategy)
        {
            BuilderStrategyChain chain = new BuilderStrategyChain();
            chain.Add(mockPlanBuilderStrategy);

            PolicyList policies = new PolicyList();

            return new DynamicMethodPlanBuilderPolicy(chain, policies);
        }
예제 #5
0
        public void CanClearPolicy()
        {
            PolicyList list = new PolicyList();
            MockPolicy policy = new MockPolicy();

            list.Set<IBuilderPolicy>(policy, typeof(string), "1");
            list.Clear<IBuilderPolicy>(typeof(string), "1");

            Assert.IsNull(list.Get<IBuilderPolicy>(typeof(string), "1"));
        }
예제 #6
0
        public void CanClearDefaultPolicy()
        {
            PolicyList list = new PolicyList();
            MockPolicy defaultPolicy = new MockPolicy();
            list.SetDefault<IBuilderPolicy>(defaultPolicy);

            list.ClearDefault<IBuilderPolicy>();

            Assert.IsNull(list.Get<IBuilderPolicy>(typeof(object), null));
        }
예제 #7
0
        public void CanClearAllPolicies()
        {
            PolicyList list = new PolicyList();
            list.Set<IBuilderPolicy>(new MockPolicy(), typeof(object), null);
            list.Set<IBuilderPolicy>(new MockPolicy(), typeof(object), "1");

            list.ClearAll();

            Assert.AreEqual(0, list.Count);
        }
        public void CreateInstanceCallDefaultExplicitConstructor()
        {
            PolicyList policies = new PolicyList();
            policies.SetDefault<IConstructorChooserPolicy>(new DefaultConstructorChooserPolicy());

            MockBuilderContext ctx = BuildContext(policies);

            MockObject mockInstance = (MockObject) ctx.HeadOfChain.BuildUp(ctx, typeof (MockObject), null, null);

            Assert.IsTrue(mockInstance.DefaultConstructorCalled);
        }
예제 #9
0
		public void SetOverwritesExistingPolicy()
		{
			PolicyList list = new PolicyList();
			MockPolicy policy1 = new MockPolicy();
			MockPolicy policy2 = new MockPolicy();

			list.Set<IBuilderPolicy>(policy1, typeof(string), "1");
			list.Set<IBuilderPolicy>(policy2, typeof(string), "1");

			Assert.AreSame(policy2, list.Get<IBuilderPolicy>(typeof(string), "1"));
		}
        public void BuildUpExecutesTwoParameterlessMethods()
        {
            PolicyList policies = new PolicyList();
            policies.SetDefault<IMethodChooserPolicy>(new AttributeBasedMethodChooser());
            MockBuilderContext ctx = BuildContext(policies);

            MockObject mockInstance = (MockObject) ctx.HeadOfChain.BuildUp(ctx, typeof (MockObject), null, null);

            Assert.IsTrue(mockInstance.InjectionMethod1Called);
            Assert.IsTrue(mockInstance.InjectionMethod2Called);
            Assert.IsFalse(mockInstance.Method3Called);
        }
예제 #11
0
        public void CanAddMultiplePoliciesToBagAndRetrieveThem()
        {
            PolicyList list = new PolicyList();
            MockPolicy policy1 = new MockPolicy();
            MockPolicy policy2 = new MockPolicy();

            list.Set<IBuilderPolicy>(policy1, typeof(object), "1");
            list.Set<IBuilderPolicy>(policy2, typeof(string), "2");

            Assert.AreSame(policy1, list.Get<IBuilderPolicy>(typeof(object), "1"));
            Assert.AreSame(policy2, list.Get<IBuilderPolicy>(typeof(string), "2"));
        }
        public void CreateInstanceCallAttributedCtor()
        {
            PolicyList policies = new PolicyList();
            policies.SetDefault<IConstructorChooserPolicy>(new AttributeBasedConstructorChooser());

            MockBuilderContext ctx = BuildContext(policies);

            MockObjectWithAttributedCtor mockInstance =
                (MockObjectWithAttributedCtor) ctx.HeadOfChain.BuildUp(ctx, typeof (MockObjectWithAttributedCtor), null, null);

            Assert.IsTrue(mockInstance.AttributedConstructorCalled);
        }
예제 #13
0
		public void SettingPolicyViaContextDoesNotAffectPoliciesPassedToContextConstructor()
		{
			PolicyList policies = new PolicyList();
			MockCreationPolicy policy1 = new MockCreationPolicy();

			policies.Set<IBuilderPolicy>(policy1, typeof (object), null);
			BuilderContext context = new BuilderContext(null, null, policies);

			MockCreationPolicy policy2 = new MockCreationPolicy();
			context.Policies.Set<IBuilderPolicy>(policy2, typeof (string), null);

			Assert.AreEqual(1, policies.Count);
		}
예제 #14
0
		public void TestSettingAndRetrievePolicy()
		{
			PolicyList policies = new PolicyList();
			MockCreationPolicy policy = new MockCreationPolicy();

			policies.Set<IBuilderPolicy>(policy, typeof (object), null);
			BuilderContext context = new BuilderContext(null, null, policies);

			IBuilderPolicy outPolicy = context.Policies.Get<IBuilderPolicy>(typeof (object), null);

			Assert.IsNotNull(outPolicy);
			Assert.AreSame(policy, outPolicy);
		}
예제 #15
0
        public void BuilderCanTakeTransientPolicies()
        {
            Builder builder = new Builder();
            Locator locator = CreateLocator();
            PolicyList policies = new PolicyList();

            PropertySetterPolicy policy = new PropertySetterPolicy();
            policy.Properties.Add("IntProp", new PropertySetterInfo("IntProp", new ValueParameter<int>(96)));
            policies.Set<IPropertySetterPolicy>(policy, typeof(PropertyObject), null);

            PropertyObject obj = builder.BuildUp<PropertyObject>(locator, null, null, policies);

            Assert.AreEqual(96, obj.IntProp);
        }
        public DefaultBuildContext(IExport targetExport, BuildMode mode, IContainer container, string contractName, 
            ErrorTracer errorTracer, BuildParameter[] parameters, IResolverExtension[] resolverExtensions)
        {
            Contract.Requires<ArgumentNullException>(targetExport != null, "targetExport");
            Contract.Requires<ArgumentNullException>(container != null, "container");
            Contract.Requires<ArgumentNullException>(errorTracer != null, "errorTracer");

            Metadata = targetExport.GetNamedExportMetadata(contractName);
            errorTracer.Export = Metadata.ToString();
            ExportType = targetExport.ImplementType;
            Target = null;
            BuildCompled = false;
            Policys = new PolicyList();
            Mode = mode;
            Container = container;
            ErrorTracer = errorTracer;
            Parameters = parameters;
            ResolverExtensions = resolverExtensions;
        }
        public void CreateInstanceUseDependencyResolverAndInjectsNamedDependency()
        {
            PolicyList policies = new PolicyList();
            MockBuilderContext ctx = BuildContext(policies);

            object dependency = new object();
            ctx.Locator.Add(new DependencyResolutionLocatorKey(typeof (object), "Foo"), dependency);

            NamedNullMockObject mockInstance =
                (NamedNullMockObject) ctx.HeadOfChain.BuildUp(ctx, typeof (NamedNullMockObject), null, null);

            Assert.IsNotNull(mockInstance);
            Assert.IsNotNull(mockInstance.DependentObject);
            Assert.AreSame(dependency, mockInstance.DependentObject);
        }
예제 #18
0
 public void Build()
 {
     var transientPolicies = new PolicyList(policies);
     var context = new BuilderContext(strategies, null, policies, transientPolicies, new NamedTypeBuildKey<object>(), null);
     Result = strategies.ExecuteBuildUp(context);
 }
예제 #19
0
 private IPolicyList GetPolicies()
 {
     PolicyList policies = new PolicyList();
     policies.Set<ILifetimePolicy>(new ContainerControlledLifetimeManager(), new NamedTypeBuildKey(typeof (object)));
     return policies;
 }
예제 #20
0
        public void CreationPolicyWillRecordSingletonsUsingLocalLifetimeContainerOnly()
        {
            BuilderStrategyChain chain = new BuilderStrategyChain();
            chain.Add(new CreationStrategy());

            Locator parentLocator = new Locator();
            LifetimeContainer container = new LifetimeContainer();
            parentLocator.Add(typeof(ILifetimeContainer), container);

            Locator childLocator = new Locator(parentLocator);

            PolicyList policies = new PolicyList();
            policies.SetDefault<ICreationPolicy>(new DefaultCreationPolicy());
            policies.SetDefault<ISingletonPolicy>(new SingletonPolicy(true));

            BuilderContext ctx = new BuilderContext(chain, childLocator, policies);

            object obj = ctx.HeadOfChain.BuildUp(ctx, typeof(object), null, null);

            Assert.IsNotNull(obj);
            Assert.IsNull(childLocator.Get(new DependencyResolutionLocatorKey(typeof(object), null)));
        }
        public void CreateInstancenotInjectsRegisteredInterfaceService()
        {
            PolicyList policies = new PolicyList();
            MockBuilderContext ctx = BuildContext(policies);
            TestableRootCompositionContainer compositionContainer = new TestableRootCompositionContainer();
            ctx.Locator.Add(new DependencyResolutionLocatorKey(typeof (CompositionContainer), null), compositionContainer);
            MockDependentObject mockDependency =
                compositionContainer.Services.AddNew<MockDependentObject, IMockDependentObject>();

            MockDependencyDependingInterface mockInstance =
                (MockDependencyDependingInterface)
                ctx.HeadOfChain.BuildUp(ctx, typeof (MockDependencyDependingInterface), null, null);

            Assert.IsNotNull(mockInstance);
            Assert.IsNotNull(mockInstance.DependentObject);
            Assert.AreSame(mockDependency, mockInstance.DependentObject);
        }
        public void CreateInstanceCreateNewDependingObject()
        {
            PolicyList policies = new PolicyList();
            MockBuilderContext ctx = BuildContext(policies);

            MockCreateNewDependingObject mockInstance =
                (MockCreateNewDependingObject) ctx.HeadOfChain.BuildUp(ctx, typeof (MockCreateNewDependingObject), null, null);

            Assert.IsNotNull(mockInstance);
            Assert.IsNotNull(mockInstance.DependentObject);
        }
        private static PolicyList GetPolicies(IConfigurationSource configurationSource)
        {
            PolicyList policyList = new PolicyList();
            policyList.Set<IConfigurationObjectPolicy>(new ConfigurationObjectPolicy(configurationSource), typeof(IConfigurationSource), null);

            return policyList;
        }
        /// <summary>
        ///     Initialisiert eine neue Instanz der <see cref="DefaultBuildContext" /> Klasse.
        /// </summary>
        /// <param name="buildObject">
        ///     The build object.
        /// </param>
        /// <param name="container">
        ///     The container.
        /// </param>
        /// <param name="errorTracer"></param>
        /// <param name="parameters"></param>
        public DefaultBuildContext([NotNull] BuildObject buildObject, [NotNull] IContainer container, [NotNull] ErrorTracer errorTracer, [CanBeNull] BuildParameter[] parameters)
        {
            Contract.Requires<ArgumentNullException>(buildObject != null, "buildObject");
            Contract.Requires<ArgumentNullException>(container != null, "container");
            Contract.Requires<ArgumentNullException>(errorTracer != null, "errorTracer");

            Metadata = buildObject.Metadata;
            errorTracer.Export = Metadata.ToString();
            Mode = BuildMode.BuildUpObject;
            Policys = new PolicyList();
            Target = buildObject.Instance;
            ExportType = Metadata.Export.ImplementType;
            BuildCompled = false;
            Container = container;
            ErrorTracer = errorTracer;
            Parameters = parameters;
        }
예제 #25
0
        public void TransientPoliciesOverrideBuilderPolicies()
        {
            Builder builder = new Builder();
            Locator locator = CreateLocator();
            PolicyList policies = new PolicyList();

            PropertySetterPolicy builderPolicy = new PropertySetterPolicy();
            builderPolicy.Properties.Add("IntProp", new PropertySetterInfo("IntProp", new ValueParameter<int>(11)));
            builder.Policies.Set<IPropertySetterPolicy>(builderPolicy, typeof(PropertyObject), null);

            PropertySetterPolicy transientPolicy = new PropertySetterPolicy();
            transientPolicy.Properties.Add("IntProp", new PropertySetterInfo("IntProp", new ValueParameter<int>(22)));
            policies.Set<IPropertySetterPolicy>(transientPolicy, typeof(PropertyObject), null);

            PropertyObject obj = builder.BuildUp<PropertyObject>(locator, null, null, policies);

            Assert.AreEqual(22, obj.IntProp);
        }
        private static IPlanBuilderPolicy CreatePlanBuilder(PolicyList innerPolicies)
        {
            BuilderStrategyChain chain = new BuilderStrategyChain();
            chain.Add(new CallConstructorStrategy());

            return new DynamicMethodPlanBuilderPolicy(chain, innerPolicies);
        }
        public void WhenNoConstructorChooserPolicyDefaultChooserIsUsed()
        {
            PolicyList policies = new PolicyList();

            MockBuilderContext ctx = BuildContext(policies);

            MockObject mockInstance = (MockObject) ctx.HeadOfChain.BuildUp(ctx, typeof (MockObject), null, null);

            Assert.IsTrue(mockInstance.DefaultConstructorCalled);
        }
예제 #28
0
 public FactoryContext(PolicyList policies, IStrategyChain strategies)
 {
     this.policies   = policies.Validation().NotNull("policies");
     this.strategies = strategies.Validation().NotNull("strategies");
 }
예제 #29
0
        private void InitializeBuilderState()
        {
            registeredNames = new NamedTypesRegistry(ParentNameRegistry);
            extensions = new List<UnityContainerExtension>();

            lifetimeContainer = new LifetimeContainer();
            strategies = new StagedStrategyChain<UnityBuildStage>(ParentStrategies);
            buildPlanStrategies = new StagedStrategyChain<UnityBuildStage>(ParentBuildPlanStrategies);
            policies = new PolicyList(ParentPolicies);
            policies.Set<IRegisteredNamesPolicy>(new RegisteredNamesPolicy(registeredNames), null);

            cachedStrategies = null;
            cachedStrategiesLock = new object();
        }
        public void CreateInstanceValueTypedParameterIsUnboxed()
        {
            PolicyList policies = new PolicyList();
            MockBuilderContext ctx = BuildContext(policies);

            int dependency = new int();
            ctx.Locator.Add(new DependencyResolutionLocatorKey(typeof (int), "Foo"), dependency);

            ValueTypeDependentMockObject mockInstance =
                (ValueTypeDependentMockObject) ctx.HeadOfChain.BuildUp(ctx, typeof (ValueTypeDependentMockObject), null, null);

            Assert.IsNotNull(mockInstance);
            Assert.AreEqual((int) 0, mockInstance.DependentObject);
        }
        public void CreateInstanceWithNoConstructorAtAll()
        {
            PolicyList policies = new PolicyList();
            policies.SetDefault<IConstructorChooserPolicy>(new DefaultConstructorChooserPolicy());

            MockBuilderContext ctx = BuildContext(policies);

            int mockInstance = (int) ctx.HeadOfChain.BuildUp(ctx, typeof (int), null, null);

            //Int instances have zero as initialization value
            Assert.AreEqual((int) 0, mockInstance);
        }
예제 #32
0
        ValueTask <object?> IUnityContainerAsync.ResolveAsync(Type type, string?name, params ResolverOverride[] overrides)
        {
            var key      = new HashKey(type ?? throw new ArgumentNullException(nameof(type)), name);
            var pipeline = TryGetPipeline(ref key);

            // Check if already got value
            if (pipeline?.Target is LifetimeManager manager)
            {
                // Make unblocking check for result
                var value = manager.TryGet(LifetimeContainer);
                if (LifetimeManager.NoValue != value)
                {
                    return(new ValueTask <object?>(value));
                }
            }

            return(new ValueTask <object?>(Task.Factory.StartNew <object?>(delegate
            {
                if (null == pipeline)
                {
                    pipeline = GetPipeline(ref key);
                }

                // Check if already created and acquire a lock if not
                var manager = pipeline.Target as LifetimeManager;
                if (null != manager)
                {
                    // Make blocking check for result
                    var value = manager.Get(LifetimeContainer);
                    if (LifetimeManager.NoValue != value)
                    {
                        return value;
                    }
                }

                // Setup Context
                var synchronized = manager as SynchronizedLifetimeManager;
                var context = new PipelineContext
                {
                    List = new PolicyList(),
                    Type = type,
                    Overrides = overrides,
                    ContainerContext = manager is ContainerControlledLifetimeManager container
                                     ? (ContainerContext)container.Scope
                                     : Context,
                };

                // Execute pipeline
                try
                {
                    var value = pipeline(ref context);
                    manager?.Set(value, LifetimeContainer);
                    return value;
                }
                catch (Exception ex)
                {
                    synchronized?.Recover();

                    if (ex is InvalidRegistrationException ||
                        ex is CircularDependencyException ||
                        ex is ObjectDisposedException)
                    {
                        var message = CreateErrorMessage(ex);
                        throw new ResolutionFailedException(context.Type, context.Name, message, ex);
                    }
                    else
                    {
                        throw;
                    }
                }
            })));