public object Resolve(IBuilderContext context) { Guard.ArgumentNotNull(context, "context"); NamedTypeBuildKey key = new NamedTypeBuildKey(type, name); IBuilderContext recursiveContext = context.CloneForNewBuild(key, null); return recursiveContext.Strategies.ExecuteBuildUp(recursiveContext); }
/// <summary> /// Initialize a new instance of the <see cref="Interceptor"/> class with a given /// name and type that will be resolved to provide interception. /// </summary> /// <param name="interceptorType">Type of the interceptor</param> /// <param name="name">name to use to resolve.</param> public Interceptor(Type interceptorType, string name) { Guard.ArgumentNotNull(interceptorType, "interceptorType"); Guard.TypeIsAssignable(typeof(IInterceptor), interceptorType, "interceptorType"); buildKey = new NamedTypeBuildKey(interceptorType, name); }
/// <summary> /// Configures the container. /// </summary> /// <param name="container">The container.</param> protected override void ConfigureContainer(IUnityContainer container) { if (Interceptor == null) { return; } var interceptorType = TypeResolver.ResolveType(Interceptor.TypeName); if (!typeof (IInstanceInterceptor).IsAssignableFrom(interceptorType)) { throw new ConfigurationErrorsException(Resources.ExceptionOnlyInstanceInterceptorBeSupported); } var builderName = interceptorType.AssemblyQualifiedName; var source = Interceptor.Injection.SelectMany( (InjectionMemberElement element) => element.GetInjectionMembers(container, typeof (IInstanceInterceptor), interceptorType, builderName)); container.RegisterType(typeof (IInstanceInterceptor), interceptorType, builderName, new ContainerControlledLifetimeManager(), source.ToArray()); var buildKey = new NamedTypeBuildKey(typeof (IInstanceInterceptor), builderName); var instance = new ResolvedAutoInterceptorPolicy( (NamedTypeBuildKey key) => container.Resolve<IInstanceInterceptor>(key.Name), buildKey); container.RegisterInstance(typeof (AutoInterceptorPolicy), typeof (AutoInterceptorPolicy).AssemblyQualifiedName, instance, new ContainerControlledLifetimeManager()); }
/// <summary> /// /// </summary> /// <param name="interceptorResolver"></param> /// <param name="buildKey"></param> public ResolvedAutoInterceptorPolicy(Func<NamedTypeBuildKey, IInstanceInterceptor> interceptorResolver, NamedTypeBuildKey buildKey) { Guard.ArgumentNotNull(interceptorResolver, "interceptorResolver"); Guard.ArgumentNotNull(buildKey, "buildKey"); this.BuildKey = buildKey; this.InterceptorResolver = interceptorResolver; }
internal ContainerRegistration(Type registeredType, string name, IPolicyList policies) { this.buildKey = new NamedTypeBuildKey(registeredType, name); MappedToType = GetMappedType(policies); LifetimeManagerType = GetLifetimeManagerType(policies); LifetimeManager = GetLifetimeManager(policies); }
private void OnRegisterInstance(object sender, RegisterInstanceEventArgs e) { Context.RegisterNamedType(e.RegisteredType, e.Name); SetLifetimeManager(e.RegisteredType, e.Name, e.LifetimeManager); NamedTypeBuildKey identityKey = new NamedTypeBuildKey(e.RegisteredType, e.Name); Context.Policies.Set<IBuildKeyMappingPolicy>(new BuildKeyMappingPolicy(identityKey), identityKey); e.LifetimeManager.SetValue(e.Instance); }
/// <summary> /// Add policies to the <paramref name="policies"/> to configure the container with /// an appropriate <see cref="IInstanceInterceptionPolicy"/> /// </summary> /// <param name="serviceType">Type of the interface being registered. This parameter is /// ignored by this class.</param> /// <param name="implementationType">Type to register.</param> /// <param name="name">Name used to resolve the type object.</param> /// <param name="policies">Policy list to add policies to.</param> public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies) { var key = new NamedTypeBuildKey(implementationType); policies.Set<IInstanceInterceptionPolicy>(new FixedInstanceInterceptionPolicy(Interceptor), key); var piabInjectionMember = new InterceptionBehavior<PolicyInjectionBehavior>(); piabInjectionMember.AddPolicies(serviceType, implementationType, name, policies); }
/// <summary> /// Get the value for a dependency. /// </summary> /// <param name="context">Current build context.</param> /// <returns>The value for the dependency.</returns> public object Resolve(IBuilderContext context) { if (context == null) { throw new ArgumentNullException("context"); } var buildKey = new NamedTypeBuildKey(typeToBuild); return context.NewBuildUp(buildKey); }
public void CanMapGenericTypeToNewGenericType() { var original = new NamedTypeBuildKey(typeof (IList<int>)); var expected = new NamedTypeBuildKey(typeof (List<int>)); IBuildKeyMappingPolicy policy = new GenericTypeBuildKeyMappingPolicy(new NamedTypeBuildKey(typeof (List<>))); var result = policy.Map(original, null); Assert.AreEqual(expected, result); }
public void CanMapGenericTypeFromNamedTypeBuildKey() { NamedTypeBuildKey original = new NamedTypeBuildKey(typeof (IList<string>), "test"); IBuildKeyMappingPolicy policy = new GenericTypeBuildKeyMappingPolicy(new NamedTypeBuildKey(typeof (List<>), "test")); NamedTypeBuildKey result = policy.Map(original, null); Assert.AreEqual(typeof (List<string>), result.Type); Assert.AreEqual(original.Name, result.Name); }
public BuildTreeItemNode(NamedTypeBuildKey buildKey, Boolean nodeCreatedByContainer, BuildTreeItemNode parentNode) { Contract.Requires<ArgumentNullException>(buildKey != null); BuildKey = buildKey; NodeCreatedByContainer = nodeCreatedByContainer; Parent = parentNode; Children = new Collection<BuildTreeItemNode>(); }
/// <summary> /// Maps the build key. /// </summary> /// <param name="buildKey">The build key to map.</param> /// <param name="context">Current build context. Used for contextual information /// if writing a more sophisticated mapping.</param> /// <returns>The new build key.</returns> public NamedTypeBuildKey Map(NamedTypeBuildKey buildKey, IBuilderContext context) { Guard.ArgumentNotNull(buildKey, "buildKey"); Type originalType = buildKey.Type; GuardSameNumberOfGenericArguments(originalType); Type[] genericArguments = originalType.GetGenericArguments(); Type resultType = destinationKey.Type.MakeGenericType(genericArguments); return new NamedTypeBuildKey(resultType, destinationKey.Name); }
// Checks if the instance being resolved has a lifetime manager factory private static bool HasLifetimeFactoryPolicy(IBuilderContext context) { var openGenericBuildKey = new NamedTypeBuildKey(context.BuildKey.Type.GetGenericTypeDefinition(), context.BuildKey.Name); IPolicyList factorySource; var factoryPolicy = context.Policies.Get<ILifetimeFactoryPolicy>(openGenericBuildKey, out factorySource); return factoryPolicy != null; }
void ApplyPolicies(Type type) { if(type == null) return; var key = new NamedTypeBuildKey(type); Context.Policies.Set<IConstructorSelectorPolicy>(new ConstructorSelectorPolicy(), key); Context.Policies.Set<IPropertySelectorPolicy>(new PropertySelectorPolicy(), key); }
private static bool RequestIsForValidatorOfT(NamedTypeBuildKey key) { var typeToBuild = key.Type; if(!typeToBuild.IsGenericType) return false; if(typeToBuild.GetGenericTypeDefinition() != typeof(Validator<>)) return false; return true; }
private IBuilderContext GetContext(IBuilderContext originalContext, NamedTypeBuildKey buildKey, DynamicBuildPlanGenerationContext ilContext) { return new BuilderContext( strategies.MakeStrategyChain(), originalContext.Lifetime, originalContext.PersistentPolicies, originalContext.Policies, buildKey, ilContext); }
/// <summary> /// Create a new <see cref="BuilderContext"/> using the explicitly provided /// values. /// </summary> /// <param name="chain">The <see cref="IStrategyChain"/> to use for this context.</param> /// <param name="lifetime">The <see cref="ILifetimeContainer"/> to use for this context.</param> /// <param name="persistentPolicies">The set of persistent policies to use for this context.</param> /// <param name="transientPolicies">The set of transient policies to use for this context. It is /// the caller's responsibility to ensure that the transient and persistent policies are properly /// combined.</param> /// <param name="buildKey">Build key for this context.</param> /// <param name="existing">Existing object to build up.</param> public BuilderContext(IStrategyChain chain, ILifetimeContainer lifetime, IPolicyList persistentPolicies, IPolicyList transientPolicies, NamedTypeBuildKey buildKey, object existing) { this.chain = chain; this.lifetime = lifetime; this.persistentPolicies = persistentPolicies; this.policies = transientPolicies; this.originalBuildKey = buildKey; this.BuildKey = buildKey; this.Existing = existing; }
public void CanCreateObjectWithoutExplicitConstructorDefined() { MockBuilderContext context = GetContext(); var key = new NamedTypeBuildKey<InternalObjectWithoutExplicitConstructor>(); IBuildPlanPolicy plan = GetPlanCreator(context).CreatePlan(context, key); context.BuildKey = key; plan.BuildUp(context); var result = (InternalObjectWithoutExplicitConstructor)context.Existing; Assert.IsNotNull(result); }
public GenericTypeBuildKeyMappingPolicy(NamedTypeBuildKey destinationKey) { Guard.ArgumentNotNull(destinationKey, "destinationKey"); if (!destinationKey.Type.GetTypeInfo().IsGenericTypeDefinition) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.MustHaveOpenGenericType, destinationKey.Type.GetTypeInfo().Name)); } this.destinationKey = destinationKey; }
public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies) { var key = new NamedTypeBuildKey(implementationType, name); var policy = policies.Get<InterceptorPolicy>(key); if (policy == null) { policy = new InterceptorPolicy(); policies.Set(policy, key); } policy.AddInterceptor(this.interceptorContainer); }
public void AssignInstanceToCurrentTreeNode(NamedTypeBuildKey buildKey, object instance) { if (_currentBuildNode.BuildKey != buildKey) { throw new InvalidOperationException( String.Format( "Build tree constructed out of order. Build key '{0}' was expected but build key '{1}' was provided.", _currentBuildNode.BuildKey, buildKey)); } _currentBuildNode.AssignInstance(instance); }
/// <summary> /// Create a new <see cref="BuilderContext"/> using the explicitly provided /// values. /// </summary> /// <param name="chain">The <see cref="IStrategyChain"/> to use for this context.</param> /// <param name="lifetime">The <see cref="ILifetimeContainer"/> to use for this context.</param> /// <param name="persistentPolicies">The set of persistent policies to use for this context.</param> /// <param name="transientPolicies">The set of transient policies to use for this context. It is /// the caller's responsibility to ensure that the transient and persistent policies are properly /// combined.</param> /// <param name="buildKey">Build key for this context.</param> /// <param name="existing">Existing object to build up.</param> public BuilderContext(IStrategyChain chain, ILifetimeContainer lifetime, IPolicyList persistentPolicies, IPolicyList transientPolicies, NamedTypeBuildKey buildKey, object existing) { this.chain = chain; this.lifetime = lifetime; this.persistentPolicies = persistentPolicies; this.policies = transientPolicies; this.originalBuildKey = buildKey; this.BuildKey = buildKey; this.Existing = existing; this.resolverOverrides = new CompositeResolverOverride(); this.ownsOverrides = true; }
private void AddPublicationsToPolicy(NamedTypeBuildKey buildKey, EventBrokerInfoPolicy policy) { Type t = buildKey.Type; foreach(EventInfo eventInfo in t.GetEvents()) { PublishesAttribute[] attrs = (PublishesAttribute[])eventInfo.GetCustomAttributes(typeof(PublishesAttribute), true); if(attrs.Length > 0) { policy.AddPublication(attrs[0].EventName, eventInfo.Name); } } }
public IBuildPlanPolicy CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey) { Guard.ArgumentNotNull(buildKey, "buildKey"); DynamicBuildPlanGenerationContext generatorContext = new DynamicBuildPlanGenerationContext(buildKey.Type); IBuilderContext planContext = GetContext(context, buildKey, generatorContext); planContext.Strategies.ExecuteBuildUp(planContext); return new DynamicMethodBuildPlan(generatorContext.GetBuildMethod()); }
public void CanCreatePlanAndExecuteItForPrivateClassWhenInFullTrust() { MockBuilderContext context = GetContext(); var key = new NamedTypeBuildKey<PrivateClassWithoutExplicitConstructor>(); IBuildPlanPolicy plan = GetPlanCreator(context).CreatePlan(context, key); context.BuildKey = key; plan.BuildUp(context); Assert.IsNotNull(context.Existing); Assert.IsInstanceOfType(context.Existing, typeof (PrivateClassWithoutExplicitConstructor)); }
private void AddSubscriptionsToPolicy(NamedTypeBuildKey buildKey, EventBrokerInfoPolicy policy) { foreach(MethodInfo method in buildKey.Type.GetMethods()) { SubscribesToAttribute[] attrs = (SubscribesToAttribute[]) method.GetCustomAttributes(typeof(SubscribesToAttribute), true); if(attrs.Length > 0) { policy.AddSubscription(attrs[0].EventName, method); } } }
/// <summary> /// Construct a build plan. /// </summary> /// <param name="context">The current build context.</param> /// <param name="buildKey">The current build key.</param> /// <returns>The created build plan.</returns> public IBuildPlanPolicy CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey) { IDynamicBuilderMethodCreatorPolicy methodCreatorPolicy = context.Policies.Get<IDynamicBuilderMethodCreatorPolicy>(context.BuildKey); DynamicBuildPlanGenerationContext generatorContext = new DynamicBuildPlanGenerationContext( buildKey.Type, methodCreatorPolicy); IBuilderContext planContext = GetContext(context, buildKey, generatorContext); planContext.Strategies.ExecuteBuildUp(planContext); return new DynamicMethodBuildPlan(generatorContext.GetBuildMethod()); }
private void OnRegisterInstance(object sender, RegisterInstanceEventArgs e) { Context.RegisterNamedType(e.RegisteredType, e.Name); SetLifetimeManager(e.RegisteredType, e.Name, e.LifetimeManager); NamedTypeBuildKey identityKey = new NamedTypeBuildKey(e.RegisteredType, e.Name); Context.Policies.Set<IBuildKeyMappingPolicy>(new BuildKeyMappingPolicy(identityKey), identityKey); if (e.LifetimeManager is SynchronizedLifetimeManager) { // workaround to prevent a SynchronizationLockException from being thrown and caught e.LifetimeManager.GetValue(); } e.LifetimeManager.SetValue(e.Instance); }
/// <summary> /// Initialize a new instance of the <see cref = "BuilderContext" /> class with a <see cref = "IStrategyChain" />, /// <see cref = "ILifetimeContainer" />, <see cref = "IPolicyList" /> and the /// build key used to start this build operation. /// </summary> /// <param name = "chain">The <see cref = "IStrategyChain" /> to use for this context.</param> /// <param name = "lifetime">The <see cref = "ILifetimeContainer" /> to use for this context.</param> /// <param name = "policies">The <see cref = "IPolicyList" /> to use for this context.</param> /// <param name = "originalBuildKey">Build key to start building.</param> /// <param name = "existing">The existing object to build up.</param> public BuilderContext(IStrategyChain chain, ILifetimeContainer lifetime, IPolicyList policies, NamedTypeBuildKey originalBuildKey, object existing) { this.chain = chain; this.lifetime = lifetime; this.originalBuildKey = originalBuildKey; BuildKey = originalBuildKey; persistentPolicies = policies; this.policies = new PolicyList(persistentPolicies); Existing = existing; }
public void PolicyThrowsIfWrongNumberOfGenericParameters() { var original = new NamedTypeBuildKey(typeof(IList<string>)); IBuildKeyMappingPolicy policy = new GenericTypeBuildKeyMappingPolicy(new NamedTypeBuildKey(typeof(Dictionary<,>))); try { policy.Map(original, null); Assert.Fail("Expected exception"); } catch (ArgumentException) { // expected } }
public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies) { var serviceTypeBuildKey = new NamedTypeBuildKey(serviceType, name); policies.Clear <IBuildKeyMappingPolicy>(serviceTypeBuildKey); var buildKey = new NamedTypeBuildKey(implementationType, name); policies.Clear <IBuildKeyMappingPolicy>(buildKey); policies.Clear <IConstructorSelectorPolicy>(buildKey); policies.Clear <IBuildPlanCreatorPolicy>(buildKey); policies.Clear <IBuildPlanPolicy>(buildKey); policies.Clear <IMethodSelectorPolicy>(buildKey); policies.Clear <IPropertySelectorPolicy>(buildKey); policies.Clear <ILifetimeFactoryPolicy>(buildKey); policies.Clear <ILifetimePolicy>(buildKey); policies.Clear <IBuilderPolicy>(buildKey); DependencyResolverTrackerPolicy.RemoveResolvers(policies, buildKey); }
public void CreateDatabaseForInvalidNameThrows() { BuilderContext context = new BuilderContext( new StrategyChain(new object[] { new MockFactoryStrategy( new DatabaseCustomFactory(), new SystemConfigurationSource(), new ConfigurationReflectionCache()) }), null, null, new PolicyList(), NamedTypeBuildKey.Make <Database>("a bad name"), null); context.Strategies.ExecuteBuildUp(context); }
public void ReflectingOverSubscribingTypeResultsInCorrectPolicy() { MockBuilderContext context = CreateContext(); NamedTypeBuildKey buildKey = NamedTypeBuildKey.Make <OneEventSubscriber>(); context.ExecuteBuildUp(buildKey, null); IEventBrokerInfoPolicy policy = context.Policies.Get <IEventBrokerInfoPolicy>(buildKey); Assert.IsNotNull(policy); List <PublicationInfo> publications = new List <PublicationInfo>(policy.Publications); List <SubscriptionInfo> subscriptions = new List <SubscriptionInfo>(policy.Subscriptions); Assert.AreEqual(0, publications.Count); CollectionAssert.AreEqual(new SubscriptionInfo[] { new SubscriptionInfo("copy", typeof(OneEventSubscriber).GetMethod("OnCopy")) }, subscriptions); }
public void ReflectingOverPublishingTypeResultsInCorrectPolicy() { MockBuilderContext context = CreateContext(); NamedTypeBuildKey buildKey = NamedTypeBuildKey.Make <OneEventPublisher>(); context.ExecuteBuildUp(buildKey, null); IEventBrokerInfoPolicy policy = context.Policies.Get <IEventBrokerInfoPolicy>(buildKey); Assert.IsNotNull(policy); List <PublicationInfo> publications = new List <PublicationInfo>(policy.Publications); List <SubscriptionInfo> subscriptions = new List <SubscriptionInfo>(policy.Subscriptions); Assert.AreEqual(0, subscriptions.Count); CollectionAssert.AreEqual(new PublicationInfo[] { new PublicationInfo("paste", "Pasting") }, publications); }
private static void RegisterTypeMappings(IUnityContainer container, bool overwriteExistingMappings, Type type, string name, IEnumerable <Type> fromTypes, Dictionary <NamedTypeBuildKey, Type> mappings) { foreach (var fromType in fromTypes.Where(t => t != typeof(IDisposable))) { if (!overwriteExistingMappings) { var key = new NamedTypeBuildKey(fromType, name); Type currentMappedToType; if (mappings.TryGetValue(key, out currentMappedToType) && (type != currentMappedToType)) { throw new DuplicateTypeMappingException(name, fromType, currentMappedToType, type); } mappings[key] = type; } container.RegisterType(fromType, type, name); } }
public void ExceptionThrownWhileSettingAPropertyIsBubbledUpAndTheCurrentOperationIsNotCleared() { MockBuilderContext context = GetContext(); var key = new NamedTypeBuildKey <OneExceptionThrowingPropertyClass>(); context.BuildKey = key; context.Existing = new OneExceptionThrowingPropertyClass(); IBuildPlanPolicy plan = GetPlanCreator(context).CreatePlan(context, key); var exception = Assert.Throws <ArgumentException>(() => plan.BuildUp(context)); var operation = context.CurrentOperation as SettingPropertyOperation; Assert.NotNull(operation); Assert.IsType <OneExceptionThrowingPropertyClass>(operation.TypeBeingConstructed); Assert.Equal("Key", operation.PropertyName); }
void IContainerPolicyCreator.CreatePolicies( IPolicyList policyList, string instanceName, ConfigurationElement configurationObject, IConfigurationSource configurationSource) { ReplaceHandlerData castConfigurationObject = (ReplaceHandlerData)configurationObject; new PolicyBuilder <ReplaceHandler, ReplaceHandlerData>( NamedTypeBuildKey.Make <ReplaceHandler>(instanceName), castConfigurationObject, c => new ReplaceHandler( new ResourceStringResolver( c.ExceptionMessageResourceType, c.ExceptionMessageResourceName, c.ExceptionMessage), c.ReplaceExceptionType)) .AddPoliciesToPolicyList(policyList); }
public void StrategyProperlyWiresEvents() { MockBuilderContext context = CreateContext(); NamedTypeBuildKey buildKey = NamedTypeBuildKey.Make <ClipboardManager>(); EventBroker broker = new EventBroker(); var brokerLifetime = new ExternallyControlledLifetimeManager(); brokerLifetime.SetValue(broker); context.Policies.Set <ILifetimePolicy>(brokerLifetime, NamedTypeBuildKey.Make <EventBroker>()); EventBrokerInfoPolicy policy = new EventBrokerInfoPolicy(); policy.AddPublication("cut", "Cut"); policy.AddPublication("copy", "Copy"); policy.AddPublication("paste", "Paste"); policy.AddSubscription("copy", typeof(ClipboardManager).GetMethod("OnCopy")); policy.AddSubscription("clipboard data available", typeof(ClipboardManager).GetMethod("OnClipboardDataAvailable")); context.Policies.Set <IEventBrokerInfoPolicy>(policy, buildKey); ClipboardManager existing = new ClipboardManager(); context.ExecuteBuildUp(buildKey, existing); List <string> registeredEvents = new List <string>(broker.RegisteredEvents); registeredEvents.Sort(); List <string> expectedEvents = new List <string>(new string[] { "cut", "copy", "paste", "clipboard data available" }); expectedEvents.Sort(); CollectionAssert.AreEqual(expectedEvents, registeredEvents); }
public void ExceptionIfNoWireupNeededAndNoBroker() { MockBuilderContext context = CreateContext(); NamedTypeBuildKey buildKey = NamedTypeBuildKey.Make <object>(); EventBrokerInfoPolicy policy = new EventBrokerInfoPolicy(); context.Policies.Set <IEventBrokerInfoPolicy>(policy, buildKey); try { context.ExecuteBuildUp(buildKey, new object()); } catch (Exception) { // If we got here, we're ok return; } Assert.Fail("No exception Occurred"); }
public void ResolvingAParameterSetsTheCurrentOperation() { var resolverPolicy = new CurrentOperationSensingResolverPolicy <object>(); MockBuilderContext context = GetContext(); var key = new NamedTypeBuildKey <ObjectWithSingleInjectionMethod>(); context.BuildKey = key; context.Existing = new ObjectWithSingleInjectionMethod(); context.Policies.Set <IMethodSelectorPolicy>( new TestSingleArgumentMethodSelectorPolicy <ObjectWithSingleInjectionMethod>(resolverPolicy), key); IBuildPlanPolicy plan = GetPlanCreator(context).CreatePlan(context, key); plan.BuildUp(context); Assert.NotNull(resolverPolicy.CurrentOperation); }
private void Context_RegisteringInstance(object sender, RegisterInstanceEventArgs e) { if (e.LifetimeManager is ExecutionScopeLifetimeManager) { var lm = e.LifetimeManager as ExecutionScopeLifetimeManager; var key = new NamedTypeBuildKey(e.RegisteredType, e.Name); var newKey = new NamedTypeBuildKey(e.RegisteredType, $"{e.Name}_Scope_{lm.Scope.Key}"); lm.SetValue(e.Instance); Context.Policies.Clear <ILifetimePolicy>(key); Context.Policies.Set <ILifetimePolicy>(lm, newKey); Context.Policies.Set <IExecutionScopeLifetimePolicy>(lm, newKey); Context.Policies.Set <IBuildKeyMappingPolicy>(new BuildKeyMappingPolicy(newKey), key); lm.Scope.Disposed += (o, de) => { Context.Policies.Clear <ILifetimePolicy>(newKey); Context.Policies.Clear <IBuildKeyMappingPolicy>(key); }; } }
public void ResolverReturnsProperNamedObject() { string expected = "We want this one"; string notExpected = "Not this one"; var expectedKey = NamedTypeBuildKey.Make <string>("expected"); var notExpectedKey = NamedTypeBuildKey.Make <string>(); var mainContext = new Mock <IBuilderContext>(); mainContext.Setup(c => c.NewBuildUp(expectedKey)).Returns(expected); mainContext.Setup(c => c.NewBuildUp(notExpectedKey)).Returns(notExpected); var resolver = new OptionalDependencyResolverPolicy(typeof(string), "expected"); object result = resolver.Resolve(mainContext.Object); Assert.AreSame(expected, result); }
/// <summary> /// A convenience method to do a new buildup operation on an existing context. This /// overload allows you to specify extra policies which will be in effect for the duration /// of the build. /// </summary> /// <param name="newBuildKey">Key defining what to build up.</param> /// <param name="childCustomizationBlock">A delegate that takes a <see cref="IBuilderContext"/>. This /// is invoked with the new child context before the build up process starts. This gives callers /// the opportunity to customize the context for the build process.</param> /// <returns>Created object.</returns> public object NewBuildUp(NamedTypeBuildKey newBuildKey, Action <IBuilderContext> childCustomizationBlock) { var newContext = new MockBuilderContext { strategies = strategies, persistentPolicies = persistentPolicies, policies = new PolicyList(persistentPolicies), lifetime = lifetime, originalBuildKey = buildKey, buildKey = newBuildKey, existing = null }; newContext.resolverOverrides.Add(resolverOverrides); childCustomizationBlock(newContext); return(strategies.ExecuteBuildUp(newContext)); }
public void OneTypeCanPublishAndSubscribeMultipleTimes() { MockBuilderContext context = CreateContext(); NamedTypeBuildKey buildKey = NamedTypeBuildKey.Make <ClipboardManager>(); context.ExecuteBuildUp(buildKey, null); IEventBrokerInfoPolicy policy = context.Policies.Get <IEventBrokerInfoPolicy>(buildKey); Assert.IsNotNull(policy); List <PublicationInfo> publications = new List <PublicationInfo>(policy.Publications); List <SubscriptionInfo> subscriptions = new List <SubscriptionInfo>(policy.Subscriptions); publications.Sort( delegate(PublicationInfo a, PublicationInfo b) { return(a.PublishedEventName.CompareTo(b.PublishedEventName)); }); subscriptions.Sort( delegate(SubscriptionInfo a, SubscriptionInfo b) { return(a.PublishedEventName.CompareTo(b.PublishedEventName)); }); CollectionAssert.AreEqual( new PublicationInfo[] { new PublicationInfo("copy", "Copy"), new PublicationInfo("cut", "Cut"), new PublicationInfo("paste", "Paste"), }, publications); CollectionAssert.AreEqual( new SubscriptionInfo[] { new SubscriptionInfo("clipboard data available", typeof(ClipboardManager).GetMethod("OnClipboardDataAvailable")), new SubscriptionInfo("copy", typeof(ClipboardManager).GetMethod("OnCopy")), }, subscriptions); }
/// <summary> /// Add policies to the <paramref name="policies"/> to configure the container to use the represented /// <see cref="IInterceptionBehavior"/> for the supplied parameters. /// </summary> /// <param name="serviceType">Interface being registered.</param> /// <param name="implementationType">Type to register.</param> /// <param name="name">Name used to resolve the type object.</param> /// <param name="policies">Policy list to add policies to.</param> public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies) { if (_explicitBehavior != null) { var lifetimeManager = new ContainerControlledLifetimeManager(); lifetimeManager.SetValue(_explicitBehavior); var behaviorName = Guid.NewGuid().ToString(); var newBehaviorKey = new NamedTypeBuildKey(_explicitBehavior.GetType(), behaviorName); policies.Set(newBehaviorKey.Type, newBehaviorKey.Name, typeof(ILifetimePolicy), lifetimeManager); InterceptionBehaviorsPolicy behaviorsPolicy = GetBehaviorsPolicy(policies, serviceType, name); behaviorsPolicy.AddBehaviorKey(newBehaviorKey); } else { var behaviorsPolicy = GetBehaviorsPolicy(policies, serviceType, name); behaviorsPolicy.AddBehaviorKey(_behaviorKey); } }
public void ResolvingAPropertyValueSetsTheCurrentOperation() { var resolverPolicy = new CurrentOperationSensingResolverPolicy <object>(); MockBuilderContext context = GetContext(); var key = new NamedTypeBuildKey <OnePropertyClass>(); context.BuildKey = key; context.Existing = new OnePropertyClass(); context.Policies.Set <IPropertySelectorPolicy>( new TestSinglePropertySelectorPolicy <OnePropertyClass>(resolverPolicy), key); IBuildPlanPolicy plan = GetPlanCreator(context).CreatePlan(context, key); plan.BuildUp(context); Assert.NotNull(resolverPolicy.CurrentOperation); }
public override void PreBuildUp(IBuilderContext context) { base.PreBuildUp(context); if (context.Existing != null && context.Existing is IInstrumentationEventProvider) { IConfigurationSource configurationSource = GetConfigurationSource(context); ConfigurationReflectionCache reflectionCache = GetReflectionCache(context); NamedTypeBuildKey key = (NamedTypeBuildKey)context.BuildKey; string id = key.Name; InstrumentationAttachmentStrategy instrumentation = new InstrumentationAttachmentStrategy(); if (ConfigurationNameProvider.IsMadeUpName(id)) { instrumentation.AttachInstrumentation(context.Existing, configurationSource, reflectionCache); } else { instrumentation.AttachInstrumentation(id, context.Existing, configurationSource, reflectionCache); } } }
public void InstancesWithNoNameWillBeAttachedToTheirInstrumentationListeners() { DictionaryConfigurationSource configSource = new DictionaryConfigurationSource(); configSource.Add(InstrumentationConfigurationSection.SectionName, new InstrumentationConfigurationSection(true, true, true, "fooApplicationInstanceName")); UnnamedSource source = new UnnamedSource(); BuilderContext context = new BuilderContext( new StrategyChain(), null, null, new PolicyList(GetPolicies(configSource)), NamedTypeBuildKey.Make <UnnamedSource>(), source); InstrumentationStrategy strategy = new InstrumentationStrategy(); strategy.PreBuildUp(context); Assert.IsTrue(((UnnamedSource)context.Existing).IsWired); }
public void MappingStrategyActuallyReturnsTheBuildKeyThePolicySpecifies() { MockBuilderContext context = new MockBuilderContext(); NamedTypeBuildKey fromKey = new NamedTypeBuildKey(typeof(Foo), "id"); NamedTypeBuildKey toKey = new NamedTypeBuildKey(typeof(IFoo), "id"); context.Policies.Set <IBuildKeyMappingPolicy>(new BuildKeyMappingPolicy(toKey), fromKey); BuildKeyMappingStrategy strategy = new BuildKeyMappingStrategy(); context.Strategies.Add(strategy); SpyStrategy spy = new SpyStrategy(); context.Strategies.Add(spy); context.BuildKey = fromKey; context.Existing = null; context.Strategies.ExecuteBuildUp(context); Assert.IsInstanceOfType(spy.BuildKey, typeof(NamedTypeBuildKey)); Assert.AreEqual(toKey, spy.BuildKey); }
/// <summary> /// API to configure interception for a type. /// </summary> /// <param name="typeToIntercept">Type to intercept.</param> /// <param name="name">Name type is registered under.</param> /// <param name="interceptor">Interceptor to use.</param> /// <returns>This extension object.</returns> public Interception SetInterceptorFor(Type typeToIntercept, string name, ITypeInterceptor interceptor) { Guard.ArgumentNotNull(typeToIntercept, "typeToIntercept"); Guard.ArgumentNotNull(interceptor, "interceptor"); GuardTypeInterceptable(typeToIntercept, interceptor); var key = new NamedTypeBuildKey(typeToIntercept, name); var policy = new FixedTypeInterceptionPolicy(interceptor); Context.Policies.Set <ITypeInterceptionPolicy>(policy, key); // add policy injection behavior if using this configuration API to set the interceptor var interceptionBehaviorsPolicy = new InterceptionBehaviorsPolicy(); interceptionBehaviorsPolicy.AddBehaviorKey(NamedTypeBuildKey.Make <PolicyInjectionBehavior>()); Context.Policies.Set <IInterceptionBehaviorsPolicy>(interceptionBehaviorsPolicy, key); return(this); }
public void TypeMappingStrategyAllowsToInterceptNonMBROs() { Builder builder = new Builder(); PolicyList policyList = CreatePolicyList(GetInjectionSettings(), true); policyList.Set <IBuildKeyMappingPolicy>( new BuildKeyMappingPolicy(NamedTypeBuildKey.Make <ClassThatImplementsInterface>(string.Empty)), NamedTypeBuildKey.Make <IInterface>(string.Empty)); IInterface instance = (IInterface)builder.BuildUp(null, null, policyList, baseStrategyChain.MakeStrategyChain(), NamedTypeBuildKey.Make <IInterface>(string.Empty), null); Assert.IsNotNull(instance); Assert.IsTrue(RemotingServices.IsTransparentProxy(instance)); }
/// <summary> /// Run an existing object through the container and perform injection on it. /// </summary> /// <remarks> /// <para> /// This method is useful when you don'type control the construction of an /// instance (ASP.NET pages or objects created via XAML, for instance) /// but you still want properties and other injection performed. /// </para></remarks> /// <param name="typeToBuild"><see cref="Type"/> of object to perform injection on.</param> /// <param name="existing">Instance to build up.</param> /// <param name="name">name to use when looking up the typemappings and other configurations.</param> /// <param name="resolverOverrides">Any overrides for the buildup.</param> /// <returns>The resulting object. By default, this will be <paramref name="existing"/>, but /// container extensions may add things like automatic proxy creation which would /// cause this to return a different object (but still type compatible with <paramref name="typeToBuild"/>).</returns> public object BuildUp(Type typeToBuild, object existing, string name, params ResolverOverride[] resolverOverrides) { var type = typeToBuild ?? throw new ArgumentNullException(nameof(typeToBuild)); if (null != existing) { InstanceIsAssignable(type, existing, nameof(existing)); } var key = new NamedTypeBuildKey(type, name); IBuilderContext context = null; try { context = new BuilderContext(this, new StrategyChain(_strategies), _lifetimeContainer, _context, key, existing); if (null != resolverOverrides && 0 != resolverOverrides.Length) { context.AddResolverOverrides(resolverOverrides); } if (key.Type.GetTypeInfo().IsGenericTypeDefinition) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Constants.CannotResolveOpenGenericType, key.Type.FullName), nameof(key.Type)); } context.Strategies.BuildUp(context); return(context.Existing); } catch (Exception ex) { throw new ResolutionFailedException(key.Type, key.Name, ex, context); } }
public void CanResolveSimpleParameterTypes() { MockBuilderContext context = GetContext(); var key = new NamedTypeBuildKey <FileLogger>(); var lifetimePolicy = new ContainerControlledLifetimeManager(); lifetimePolicy.SetValue("C:\\Log.txt"); context.Policies.Set <ILifetimePolicy>(lifetimePolicy, new NamedTypeBuildKey <string>()); IBuildPlanPolicy plan = GetPlanCreator(context).CreatePlan(context, key); context.BuildKey = key; plan.BuildUp(context); object result = context.Existing; FileLogger logger = result as FileLogger; Assert.IsNotNull(result); Assert.IsNotNull(logger); Assert.AreEqual("C:\\Log.txt", logger.LogFile); }
void IContainerPolicyCreator.CreatePolicies( IPolicyList policyList, string instanceName, ConfigurationElement configurationObject, IConfigurationSource configurationSource) { LoggingExceptionHandlerData castConfigurationObject = (LoggingExceptionHandlerData)configurationObject; new PolicyBuilder <LoggingExceptionHandler, LoggingExceptionHandlerData>( NamedTypeBuildKey.Make <LoggingExceptionHandler>(instanceName), castConfigurationObject, c => new LoggingExceptionHandler( castConfigurationObject.LogCategory, castConfigurationObject.EventId, castConfigurationObject.Severity, castConfigurationObject.Title, castConfigurationObject.Priority, castConfigurationObject.FormatterType, Resolve.Reference <LogWriter>(null))) .AddPoliciesToPolicyList(policyList); }
public void StrategyThrowsIfWireupIsNeededAndBrokerNotInLocator() { MockBuilderContext context = CreateContext(); NamedTypeBuildKey buildKey = NamedTypeBuildKey.Make <OneEventPublisher>(); EventBrokerInfoPolicy policy = new EventBrokerInfoPolicy(); policy.AddPublication("paste", "Pasting"); context.Policies.Set <IEventBrokerInfoPolicy>(policy, buildKey); try { OneEventPublisher existing = new OneEventPublisher(); context.ExecuteBuildUp(buildKey, existing); } catch (Exception) { // If we got here, we're Ok, this is expected. return; } Assert.Fail("No exception occured"); }
public void CanCreateDatabaseForValidName() { BuilderContext context = new BuilderContext( new StrategyChain(new object[] { new MockFactoryStrategy( new DatabaseCustomFactory(), new SystemConfigurationSource(), new ConfigurationReflectionCache()) }), null, null, new PolicyList(), NamedTypeBuildKey.Make <Database>("Service_Dflt"), null); object database = context.Strategies.ExecuteBuildUp(context); Assert.IsNotNull(database); Assert.AreSame(typeof(SqlDatabase), database.GetType()); }
void IContainerPolicyCreator.CreatePolicies( IPolicyList policyList, string instanceName, ConfigurationElement configurationObject, IConfigurationSource configurationSource) { BasicCustomTraceListenerData castConfigurationObject = (BasicCustomTraceListenerData)configurationObject; string listenerName = castConfigurationObject.Name; Type listenerType = castConfigurationObject.Type; string initData = castConfigurationObject.InitData; TraceOptions traceOutputOptions = castConfigurationObject.TraceOutputOptions; NameValueCollection attributes = castConfigurationObject.Attributes; TraceFilter filter = castConfigurationObject.Filter != SourceLevels.All ? new EventTypeFilter(castConfigurationObject.Filter) : null; string formatterName = castConfigurationObject is CustomTraceListenerData ? ((CustomTraceListenerData)castConfigurationObject).Formatter : null; policyList.Set <IBuildPlanPolicy>( new DelegateBuildPlanPolicy( context => { TraceListener traceListener = SystemDiagnosticsTraceListenerCreationHelper.CreateSystemDiagnosticsTraceListener( listenerName, listenerType, initData, attributes); traceListener.Name = listenerName; traceListener.TraceOutputOptions = traceOutputOptions; traceListener.Filter = filter; CustomTraceListener customTraceListener = traceListener as CustomTraceListener; if (customTraceListener != null && !string.IsNullOrEmpty(formatterName)) { IBuilderContext formatterContext = context.CloneForNewBuild(NamedTypeBuildKey.Make <ILogFormatter>(formatterName), null); customTraceListener.Formatter = (ILogFormatter)formatterContext.Strategies.ExecuteBuildUp(formatterContext); } return(traceListener); }), new NamedTypeBuildKey(listenerType, instanceName)); }
private static SpecifiedPropertiesSelectorPolicy GetSelectorPolicy(IPolicyList policies, Type typeToInject, string name) { NamedTypeBuildKey key = new NamedTypeBuildKey(typeToInject, name); IPropertySelectorPolicy selector = policies.GetNoDefault <IPropertySelectorPolicy>(key, false); if (selector == null) { FullAutowirePropertySelectorPolicy defaultSelector = policies.Get <IPropertySelectorPolicy>(key, false) as FullAutowirePropertySelectorPolicy; if (defaultSelector != null) { selector = defaultSelector.Clone(); policies.Set(selector, key); } else { throw new InvalidOperationException("Cannot use AutiviewEnabledInjectionProperty without FullAutowireContainerExtension. Please register FullAutowireContainerExtension extension in the container."); } } return(((FullAutowirePropertySelectorPolicy)selector).SpecifiedPropertiesPolicy); }
private Type GetLifetimeManagerType(IPolicyList policies) { var key = new NamedTypeBuildKey(MappedToType, Name); var lifetime = policies.Get <ILifetimePolicy>(key); if (lifetime != null) { return(lifetime.GetType()); } if (MappedToType.GetTypeInfo().IsGenericType) { var genericKey = new NamedTypeBuildKey(MappedToType.GetGenericTypeDefinition(), Name); var lifetimeFactory = policies.Get <ILifetimeFactoryPolicy>(genericKey); if (lifetimeFactory != null) { return(lifetimeFactory.LifetimeType); } } return(typeof(TransientLifetimeManager)); }
/// <summary> /// Adds the policies describing the Data Access Application Block's objects. /// </summary> protected override void Initialize() { DatabaseConfigurationView configurationView = new DatabaseConfigurationView(ConfigurationSource); string defaultDatabaseName = configurationView.DefaultName; foreach (ConnectionStringSettings connectionStringSettings in configurationView.GetConnectionStringSettingsCollection()) { if (IsValidProviderName(connectionStringSettings.ProviderName)) { DbProviderMapping mapping = configurationView.GetProviderMapping( connectionStringSettings.Name, connectionStringSettings.ProviderName); Type databaseType = mapping.DatabaseType; // add type mapping this.Context.Policies.Set <IBuildKeyMappingPolicy>( new BuildKeyMappingPolicy(new NamedTypeBuildKey(databaseType, connectionStringSettings.Name)), NamedTypeBuildKey.Make <Database>(connectionStringSettings.Name)); // add default mapping, if appropriate if (connectionStringSettings.Name == defaultDatabaseName) { this.Context.Policies.Set <IBuildKeyMappingPolicy>( new BuildKeyMappingPolicy(new NamedTypeBuildKey(databaseType, connectionStringSettings.Name)), NamedTypeBuildKey.Make <Database>()); } // add ctor selector, based on the actual db type IContainerPolicyCreator policyCreator = GetContainerPolicyCreator(databaseType, null); policyCreator.CreatePolicies( this.Context.Policies, connectionStringSettings.Name, connectionStringSettings, this.ConfigurationSource); } } }