From: <jer...@us...> - 2007-03-25 02:56:21
|
Revision: 28 http://structuremap.svn.sourceforge.net/structuremap/?rev=28&view=rev Author: jeremydmiller Date: 2007-03-24 19:56:13 -0700 (Sat, 24 Mar 2007) Log Message: ----------- Pulling out the IInstanceManager interface Modified Paths: -------------- trunk/Source/CommonAssemblyInfo.cs trunk/Source/StructureMap/Configuration/DSL/Registry.cs trunk/Source/StructureMap/Graph/AssemblyGraph.cs trunk/Source/StructureMap/Graph/Plugin.cs trunk/Source/StructureMap/Graph/PluginGraph.cs trunk/Source/StructureMap/InstanceManager.cs trunk/Source/StructureMap/StructureMap.csproj trunk/Source/StructureMap.Testing/Configuration/DSL/AddInstanceTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/CreatePluginFamilyTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/ProfileExpressionTester.cs Added Paths: ----------- trunk/Source/StructureMap/IInstanceManager.cs Modified: trunk/Source/CommonAssemblyInfo.cs =================================================================== --- trunk/Source/CommonAssemblyInfo.cs 2007-03-25 02:43:09 UTC (rev 27) +++ trunk/Source/CommonAssemblyInfo.cs 2007-03-25 02:56:13 UTC (rev 28) @@ -1,5 +1,7 @@ +using System; using System.Reflection; using System.Runtime.InteropServices; + //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. @@ -10,10 +12,11 @@ // </auto-generated> //------------------------------------------------------------------------------ -[assembly : ComVisible(false)] -[assembly : AssemblyVersion("1.0.0.0000")] -[assembly : AssemblyCopyrightAttribute("Copyright (c) 2005, Jeremy D. Miller, Jeffrey Palermo")] -[assembly : AssemblyProductAttribute("StructureMap")] -[assembly : AssemblyCompanyAttribute("")] -[assembly : AssemblyConfigurationAttribute("release")] -[assembly : AssemblyInformationalVersionAttribute("1.0.0.0000")] \ No newline at end of file +[assembly: ComVisibleAttribute(false)] +[assembly: AssemblyVersionAttribute("1.0.0.0000")] +[assembly: AssemblyCopyrightAttribute("Copyright (c) 2005, Jeremy D. Miller, Jeffrey Palermo")] +[assembly: AssemblyProductAttribute("StructureMap")] +[assembly: AssemblyCompanyAttribute("")] +[assembly: AssemblyConfigurationAttribute("release")] +[assembly: AssemblyInformationalVersionAttribute("1.0.0.0000")] + Modified: trunk/Source/StructureMap/Configuration/DSL/Registry.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2007-03-25 02:43:09 UTC (rev 27) +++ trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2007-03-25 02:56:13 UTC (rev 28) @@ -63,7 +63,7 @@ return expression; } - public InstanceManager BuildInstanceManager() + public IInstanceManager BuildInstanceManager() { configurePluginGraph(_graph); _graph.ReadDefaults(); Modified: trunk/Source/StructureMap/Graph/AssemblyGraph.cs =================================================================== --- trunk/Source/StructureMap/Graph/AssemblyGraph.cs 2007-03-25 02:43:09 UTC (rev 27) +++ trunk/Source/StructureMap/Graph/AssemblyGraph.cs 2007-03-25 02:56:13 UTC (rev 28) @@ -158,7 +158,7 @@ public static AssemblyGraph ContainingType<T>() { - return new AssemblyGraph(typeof(T).Assembly); + return new AssemblyGraph(typeof (T).Assembly); } public Type FindTypeByFullName(string fullName) Modified: trunk/Source/StructureMap/Graph/Plugin.cs =================================================================== --- trunk/Source/StructureMap/Graph/Plugin.cs 2007-03-25 02:43:09 UTC (rev 27) +++ trunk/Source/StructureMap/Graph/Plugin.cs 2007-03-25 02:56:13 UTC (rev 28) @@ -102,7 +102,8 @@ PluggableAttribute att = PluggableAttribute.InstanceOf(pluggedType); if (att == null) { - return new Plugin(pluggedType, TypePath.GetAssemblyQualifiedName(pluggedType), Graph.DefinitionSource.Implicit); + return + new Plugin(pluggedType, TypePath.GetAssemblyQualifiedName(pluggedType), DefinitionSource.Implicit); } else { @@ -396,15 +397,17 @@ public override int GetHashCode() { - return (_pluggedType != null ? _pluggedType.GetHashCode() : 0) + 29*(_concreteKey != null ? _concreteKey.GetHashCode() : 0); + return + (_pluggedType != null ? _pluggedType.GetHashCode() : 0) + + 29*(_concreteKey != null ? _concreteKey.GetHashCode() : 0); } public string FindFirstConstructorArgumentOfType<T>() { - ConstructorInfo ctor = this.GetConstructor(); + ConstructorInfo ctor = GetConstructor(); foreach (ParameterInfo info in ctor.GetParameters()) { - if (info.ParameterType.Equals(typeof(T))) + if (info.ParameterType.Equals(typeof (T))) { return info.Name; } Modified: trunk/Source/StructureMap/Graph/PluginGraph.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginGraph.cs 2007-03-25 02:43:09 UTC (rev 27) +++ trunk/Source/StructureMap/Graph/PluginGraph.cs 2007-03-25 02:56:13 UTC (rev 28) @@ -160,7 +160,7 @@ public PluginFamily LocateOrCreateFamilyForType(Type pluginType) { buildFamilyIfMissing(pluginType); - return this.PluginFamilies[pluginType]; + return PluginFamilies[pluginType]; } private Type findTypeByFullName(string fullName) @@ -181,7 +181,5 @@ { _defaultManager.ReadDefaultsFromPluginGraph(this); } - - } } \ No newline at end of file Added: trunk/Source/StructureMap/IInstanceManager.cs =================================================================== --- trunk/Source/StructureMap/IInstanceManager.cs (rev 0) +++ trunk/Source/StructureMap/IInstanceManager.cs 2007-03-25 02:56:13 UTC (rev 28) @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using StructureMap.Graph; + +namespace StructureMap +{ + public interface IInstanceManager + { + T CreateInstance<T>(string instanceKey); + T CreateInstance<T>(); + T FillDependencies<T>(); + void Inject<T>(T instance); + IList<T> GetAllInstances<T>(); + void SetDefaultsToProfile(string profile); + + InstanceDefaultManager DefaultManager + { + get; + } + } +} \ No newline at end of file Modified: trunk/Source/StructureMap/InstanceManager.cs =================================================================== --- trunk/Source/StructureMap/InstanceManager.cs 2007-03-25 02:43:09 UTC (rev 27) +++ trunk/Source/StructureMap/InstanceManager.cs 2007-03-25 02:56:13 UTC (rev 28) @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Collections.Specialized; using NMock; using StructureMap.Exceptions; using StructureMap.Graph; @@ -12,10 +11,10 @@ /// <summary> /// A collection of IInstanceFactory's. /// </summary> - public class InstanceManager : IEnumerable + public class InstanceManager : IInstanceManager, IEnumerable { private Dictionary<Type, IInstanceFactory> _factories; - private HybridDictionary _filledTypeFactories; + private Dictionary<Type, InstanceFactory> _filledTypeFactories; private bool _failOnException = true; private GenericsPluginGraph _genericsGraph; private InstanceDefaultManager _defaultManager; @@ -26,7 +25,7 @@ public InstanceManager() { _factories = new Dictionary<Type, IInstanceFactory>(); - _filledTypeFactories = new HybridDictionary(); + _filledTypeFactories = new Dictionary<Type, InstanceFactory>(); _genericsGraph = new GenericsPluginGraph(); } @@ -174,7 +173,7 @@ public T CreateInstance<T>() { - return (T)CreateInstance(typeof(T)); + return (T) CreateInstance(typeof (T)); } /// <summary> @@ -202,7 +201,6 @@ } - /// <summary> /// Creates a new instance of the requested type using the InstanceMemento. Mostly used from other /// classes to link children members @@ -338,11 +336,11 @@ private InstanceFactory getFilledTypeFactory(Type type) { - if (!_filledTypeFactories.Contains(type)) + if (!_filledTypeFactories.ContainsKey(type)) { lock (this) { - if (!_filledTypeFactories.Contains(type)) + if (!_filledTypeFactories.ContainsKey(type)) { PluginFamily family = PluginFamily.CreateAutoFilledPluginFamily(type); InstanceFactory factory = new InstanceFactory(family, true); @@ -352,7 +350,7 @@ } } - return (InstanceFactory) _filledTypeFactories[type]; + return _filledTypeFactories[type]; } #region mocking @@ -390,14 +388,10 @@ /// <returns></returns> public bool IsMocked(Type TargetType) { - bool returnValue = false; - - returnValue = isInstanceFamilyMocked(this[TargetType]); - - return returnValue; + return isInstanceFamilyMocked(this[TargetType]); } - private bool isInstanceFamilyMocked(IInstanceFactory instanceFactory) + private static bool isInstanceFamilyMocked(IInstanceFactory instanceFactory) { bool returnValue = false; @@ -473,6 +467,11 @@ } } + public void Inject<T>(T instance) + { + InjectStub(typeof(T), instance); + } + #endregion public IEnumerator GetEnumerator() @@ -489,7 +488,7 @@ { List<T> list = new List<T>(); - foreach (T instance in this[typeof(T)].GetAllInstances()) + foreach (T instance in this[typeof (T)].GetAllInstances()) { list.Add(instance); } Modified: trunk/Source/StructureMap/StructureMap.csproj =================================================================== --- trunk/Source/StructureMap/StructureMap.csproj 2007-03-25 02:43:09 UTC (rev 27) +++ trunk/Source/StructureMap/StructureMap.csproj 2007-03-25 02:56:13 UTC (rev 28) @@ -450,6 +450,7 @@ <Compile Include="IInstanceFactory.cs"> <SubType>Code</SubType> </Compile> + <Compile Include="IInstanceManager.cs" /> <Compile Include="InstanceBuilder.cs"> <SubType>Code</SubType> </Compile> Modified: trunk/Source/StructureMap.Testing/Configuration/DSL/AddInstanceTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Configuration/DSL/AddInstanceTester.cs 2007-03-25 02:43:09 UTC (rev 27) +++ trunk/Source/StructureMap.Testing/Configuration/DSL/AddInstanceTester.cs 2007-03-25 02:56:13 UTC (rev 28) @@ -10,7 +10,7 @@ [TestFixture] public class AddInstanceTester { - private InstanceManager manager; + private IInstanceManager manager; private PluginGraph pluginGraph; [SetUp] @@ -104,7 +104,7 @@ .WithName("Orange") ); - InstanceManager mgr = registry.BuildInstanceManager(); + IInstanceManager mgr = registry.BuildInstanceManager(); ColorWidget orange = (ColorWidget) mgr.CreateInstance<IWidget>("Orange"); Assert.IsNotNull(orange); Modified: trunk/Source/StructureMap.Testing/Configuration/DSL/CreatePluginFamilyTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Configuration/DSL/CreatePluginFamilyTester.cs 2007-03-25 02:43:09 UTC (rev 27) +++ trunk/Source/StructureMap.Testing/Configuration/DSL/CreatePluginFamilyTester.cs 2007-03-25 02:56:13 UTC (rev 28) @@ -25,7 +25,7 @@ // Needs to blow up if the concrete type can't be used registry.BuildInstancesOf<Rule>().TheDefaultIsConcreteType<ARule>(); - InstanceManager manager = registry.BuildInstanceManager(); + IInstanceManager manager = registry.BuildInstanceManager(); Assert.IsInstanceOfType(typeof(ARule), manager.CreateInstance<Rule>()); } @@ -85,7 +85,7 @@ Registry.Instance<IWidget>().UsingConcreteType<ColorWidget>().WithProperty("Color").EqualTo("Red") ); - InstanceManager manager = registry.BuildInstanceManager(); + IInstanceManager manager = registry.BuildInstanceManager(); ColorWidget widget = (ColorWidget) manager.CreateInstance<IWidget>(); Assert.AreEqual("Red", widget.Color); Modified: trunk/Source/StructureMap.Testing/Configuration/DSL/ProfileExpressionTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Configuration/DSL/ProfileExpressionTester.cs 2007-03-25 02:43:09 UTC (rev 27) +++ trunk/Source/StructureMap.Testing/Configuration/DSL/ProfileExpressionTester.cs 2007-03-25 02:56:13 UTC (rev 28) @@ -46,7 +46,7 @@ Registry.Instance<IWidget>().UsingConcreteType<AWidget>() ); - InstanceManager manager = registry.BuildInstanceManager(); + IInstanceManager manager = registry.BuildInstanceManager(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <der...@us...> - 2007-07-27 13:44:01
|
Revision: 48 http://structuremap.svn.sourceforge.net/structuremap/?rev=48&view=rev Author: derrickrapp Date: 2007-07-27 06:43:55 -0700 (Fri, 27 Jul 2007) Log Message: ----------- Added support for specific implementations of generic interfaces. Such as MyIntObject : MyInterface<int> Modified Paths: -------------- trunk/Source/CommonAssemblyInfo.cs trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs trunk/Source/StructureMap/Graph/Plugin.cs trunk/Source/StructureMap/Graph/PluginFamily.cs trunk/Source/StructureMap.Testing/GenericsIntegrationTester.cs trunk/Source/StructureMap.Testing.GenericWidgets/Widgets.cs Modified: trunk/Source/CommonAssemblyInfo.cs =================================================================== --- trunk/Source/CommonAssemblyInfo.cs 2007-05-02 01:32:00 UTC (rev 47) +++ trunk/Source/CommonAssemblyInfo.cs 2007-07-27 13:43:55 UTC (rev 48) @@ -5,7 +5,7 @@ //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. -// Runtime Version:2.0.50727.42 +// Runtime Version:2.0.50727.832 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. Modified: trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs =================================================================== --- trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs 2007-05-02 01:32:00 UTC (rev 47) +++ trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs 2007-07-27 13:43:55 UTC (rev 48) @@ -7,11 +7,11 @@ { public static bool CanBeCast(Type pluginType, Type pluggedType) { - bool isGenericComparison = pluginType.IsGenericType && pluggedType.IsGenericType; - if (!isGenericComparison) - { - return false; - } + //bool isGenericComparison = pluginType.IsGenericType && pluggedType.IsGenericType; + //if (!isGenericComparison) + //{ + // return false; + //} try { Modified: trunk/Source/StructureMap/Graph/Plugin.cs =================================================================== --- trunk/Source/StructureMap/Graph/Plugin.cs 2007-05-02 01:32:00 UTC (rev 47) +++ trunk/Source/StructureMap/Graph/Plugin.cs 2007-07-27 13:43:55 UTC (rev 48) @@ -190,7 +190,15 @@ public Plugin CreateTemplatedClone(params Type[] types) { - Type templatedType = _pluggedType.MakeGenericType(types); + Type templatedType; + if (_pluggedType.IsGenericType) + { + templatedType = _pluggedType.MakeGenericType(types); + } + else + { + templatedType = _pluggedType; + } Plugin templatedPlugin = new Plugin(templatedType, _concreteKey, _definitionSource); templatedPlugin._setters = _setters; Modified: trunk/Source/StructureMap/Graph/PluginFamily.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginFamily.cs 2007-05-02 01:32:00 UTC (rev 47) +++ trunk/Source/StructureMap/Graph/PluginFamily.cs 2007-07-27 13:43:55 UTC (rev 48) @@ -1,4 +1,5 @@ using System; +using System.Reflection; using StructureMap.Interceptors; using StructureMap.Source; @@ -118,7 +119,7 @@ Type templatedType = _pluginType.MakeGenericType(templateTypes); PluginFamily templatedFamily = new PluginFamily(templatedType); templatedFamily._defaultKey = _defaultKey; - templatedFamily._source = _source; + templatedFamily._source = new MemoryMementoSource(); templatedFamily._definitionSource = _definitionSource; foreach (InstanceFactoryInterceptor interceptor in _interceptionChain) @@ -129,13 +130,50 @@ foreach (Plugin plugin in _plugins) { - Plugin templatedPlugin = plugin.CreateTemplatedClone(templateTypes); - templatedFamily.Plugins.Add(templatedPlugin); + if (IsOfCorrectGenericType(plugin, templateTypes)) + { + Plugin templatedPlugin = plugin.CreateTemplatedClone(templateTypes); + templatedFamily.Plugins.Add(templatedPlugin); + foreach (InstanceMemento memento in _source.GetAllMementos()) + { + if (memento.ConcreteKey == plugin.ConcreteKey) + { + templatedFamily._source.AddExternalMemento(memento); + } + } + } } return templatedFamily; } + private bool IsOfCorrectGenericType(Plugin plugin, params Type[] templateTypes) + { + bool isValid = true; + + Type interfaceType = plugin.PluggedType.GetInterface(_pluginType.Name); + if (interfaceType == null) + { + interfaceType = plugin.PluggedType.BaseType; + } + Type[] pluginArgs = _pluginType.GetGenericArguments(); + Type[] pluggableArgs = interfaceType.GetGenericArguments(); + + if (templateTypes.Length != pluginArgs.Length && + pluginArgs.Length != pluggableArgs.Length) + { + return false; + } + + for (int i = 0; i < templateTypes.Length; i++) + { + isValid &= templateTypes[i] == pluggableArgs[i] || + pluginArgs[i].IsGenericParameter && + pluggableArgs[i].IsGenericParameter; + } + return isValid; + } + #region properties /// <summary> Modified: trunk/Source/StructureMap.Testing/GenericsIntegrationTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/GenericsIntegrationTester.cs 2007-05-02 01:32:00 UTC (rev 47) +++ trunk/Source/StructureMap.Testing/GenericsIntegrationTester.cs 2007-07-27 13:43:55 UTC (rev 48) @@ -1,3 +1,5 @@ +using System.Collections; +using System.Collections.Generic; using NUnit.Framework; using StructureMap.Graph; using StructureMap.Testing.GenericWidgets; @@ -86,5 +88,28 @@ Assert.AreNotSame(object1, object4); } + + [Test] + public void AllTypesWithSpecificImplementation() + { + IList objectConcepts = manager.GetAllInstances(typeof(IConcept<object>)); + + Assert.IsNotNull(objectConcepts); + Assert.AreEqual(2, objectConcepts.Count); + + IList stringConcepts = manager.GetAllInstances(typeof(IConcept<string>)); + + Assert.IsNotNull(stringConcepts); + Assert.AreEqual(1, stringConcepts.Count); + } + + [Test] + public void SpecificImplementation() + { + IConcept<object> concept = (IConcept<object>)manager.CreateInstance(typeof(IConcept<object>), "Specific"); + + Assert.IsNotNull(concept); + Assert.IsInstanceOfType(typeof(SpecificConcept), concept); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap.Testing.GenericWidgets/Widgets.cs =================================================================== --- trunk/Source/StructureMap.Testing.GenericWidgets/Widgets.cs 2007-05-02 01:32:00 UTC (rev 47) +++ trunk/Source/StructureMap.Testing.GenericWidgets/Widgets.cs 2007-07-27 13:43:55 UTC (rev 48) @@ -57,6 +57,21 @@ } } + [PluginFamily("Default")] + public interface IConcept<T> + { + } + + [Pluggable("Default")] + public class GenericConcept<T> : IConcept<T> + { + } + + [Pluggable("Specific")] + public class SpecificConcept : IConcept<object> + { + } + public interface IThing<T, U> { } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jer...@us...> - 2007-12-14 11:16:42
|
Revision: 49 http://structuremap.svn.sourceforge.net/structuremap/?rev=49&view=rev Author: jeremydmiller Date: 2007-12-14 03:16:38 -0800 (Fri, 14 Dec 2007) Log Message: ----------- Configuration changes for the dynamic injection Modified Paths: -------------- trunk/Source/StructureMap/Configuration/DSL/CreatePluginFamilyExpression.cs trunk/Source/StructureMap/Configuration/DSL/LiteralMemento.cs trunk/Source/StructureMap/Configuration/DSL/Registry.cs trunk/Source/StructureMap/Graph/Plugin.cs trunk/Source/StructureMap/Graph/PluginCollection.cs trunk/Source/StructureMap/Graph/PluginFamily.cs trunk/Source/StructureMap/IInstanceFactory.cs trunk/Source/StructureMap/IInstanceManager.cs trunk/Source/StructureMap/InstanceBuilder.cs trunk/Source/StructureMap/InstanceFactory.cs trunk/Source/StructureMap/InstanceManager.cs trunk/Source/StructureMap/Interceptors/InstanceFactoryInterceptor.cs trunk/Source/StructureMap/MemoryInstanceMemento.cs trunk/Source/StructureMap/ObjectFactory.cs trunk/Source/StructureMap/StructureMap.csproj trunk/Source/StructureMap/StructureMapException.resx trunk/Source/StructureMap.Testing/Configuration/DSL/RegistryIntegratedTester.cs trunk/Source/StructureMap.Testing/Container/FillDependenciesTester.cs trunk/Source/StructureMap.Testing/Container/FullStackFacadeTester.cs trunk/Source/StructureMap.Testing/Container/InstanceFactoryTester.cs trunk/Source/StructureMap.Testing/Container/MockingTester.cs trunk/Source/StructureMap.Testing/ObjectMother.cs trunk/Source/StructureMap.Testing/StructureMap.Testing.csproj trunk/Source/StructureMap.sln Added Paths: ----------- trunk/Source/StructureMap/Configuration/DSL/ConstructorExpression.cs trunk/Source/StructureMap/ConstructorMemento.cs trunk/Source/StructureMap.Testing/Configuration/DSL/ConstructorExpressionTester.cs trunk/Source/StructureMap.Testing/ConstructorMementoTester.cs trunk/Source/StructureMap.Testing/Container/DynamicInjectionTester.cs Removed Paths: ------------- trunk/Source/StructureMap/MockInstanceFactory.cs trunk/Source/StructureMap/StubbedInstanceFactory.cs trunk/Source/StructureMap.Testing/Container/StubbedInstanceFactoryTester.cs Added: trunk/Source/StructureMap/Configuration/DSL/ConstructorExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/ConstructorExpression.cs (rev 0) +++ trunk/Source/StructureMap/Configuration/DSL/ConstructorExpression.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -0,0 +1,49 @@ +using System; +using StructureMap.Graph; + +namespace StructureMap.Configuration.DSL +{ + public class ConstructorExpression<PLUGINTYPE> : MementoBuilder<ConstructorExpression<PLUGINTYPE>> + { + private ConstructorMemento<PLUGINTYPE> _memento; + + public ConstructorExpression(BuildObjectDelegate<PLUGINTYPE> builder) + : base(typeof (PLUGINTYPE)) + { + _memento.Builder = builder; + } + + + protected override InstanceMemento memento + { + get { return _memento; } + } + + protected override ConstructorExpression<PLUGINTYPE> thisInstance + { + get { return this; } + } + + protected override void configureMemento(PluginFamily family) + { + } + + protected override void validate() + { + } + + protected override void buildMemento() + { + _memento = new ConstructorMemento<PLUGINTYPE>(); + } + + public override void ValidatePluggability(Type pluginType) + { + if (!pluginType.Equals(typeof(PLUGINTYPE))) + { + throw new StructureMapException(306, + typeof (PLUGINTYPE).FullName, pluginType.FullName); + } + } + } +} \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/DSL/CreatePluginFamilyExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/CreatePluginFamilyExpression.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/Configuration/DSL/CreatePluginFamilyExpression.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -65,20 +65,34 @@ return this; } + public CreatePluginFamilyExpression AddInstance(IMementoBuilder builder) + { + builder.ValidatePluggability(_pluginType); + + _children.Add(builder); + _alterations.Add(delegate (PluginFamily family) + { + InstanceMemento memento = builder.BuildMemento(family); + family.Source.AddExternalMemento(memento); + }); + + return this; + } + /// <summary> /// Convenience method that sets the default concrete type of the PluginType. Type T /// can only accept types that do not have any primitive constructor arguments. /// StructureMap has to know how to construct all of the constructor argument types. /// </summary> - /// <typeparam name="T"></typeparam> + /// <typeparam name="CONCRETETYPE"></typeparam> /// <returns></returns> - public CreatePluginFamilyExpression TheDefaultIsConcreteType<T>() + public CreatePluginFamilyExpression TheDefaultIsConcreteType<CONCRETETYPE>() { - ExpressionValidator.ValidatePluggabilityOf(typeof (T)).IntoPluginType(_pluginType); + ExpressionValidator.ValidatePluggabilityOf(typeof (CONCRETETYPE)).IntoPluginType(_pluginType); _alterations.Add(delegate(PluginFamily family) { - Plugin plugin = family.Plugins.FindOrCreate(typeof (T)); + Plugin plugin = family.Plugins.FindOrCreate(typeof (CONCRETETYPE)); family.DefaultInstanceKey = plugin.ConcreteKey; }); @@ -112,5 +126,7 @@ delegate(PluginFamily family) { family.InterceptionChain.AddInterceptor(new SingletonInterceptor()); }); return this; } + + } } \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/DSL/LiteralMemento.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/LiteralMemento.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/Configuration/DSL/LiteralMemento.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -9,8 +9,14 @@ public LiteralMemento(object instance) { _instance = instance; + InstanceKey = Guid.NewGuid().ToString(); } + public LiteralMemento Named(string name) + { + InstanceKey = name; + return this; + } public object Instance { Modified: trunk/Source/StructureMap/Configuration/DSL/Registry.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -52,16 +52,32 @@ /// Direct StructureMap to build instances of type T, and look for concrete classes /// marked with the [Pluggable] attribute that implement type T /// </summary> - /// <typeparam name="T"></typeparam> + /// <typeparam name="PLUGINTYPE"></typeparam> /// <returns></returns> - public CreatePluginFamilyExpression BuildInstancesOf<T>() + public CreatePluginFamilyExpression BuildInstancesOf<PLUGINTYPE>() { - CreatePluginFamilyExpression expression = new CreatePluginFamilyExpression(typeof (T)); + CreatePluginFamilyExpression expression = new CreatePluginFamilyExpression(typeof (PLUGINTYPE)); addExpression(expression); return expression; } + /// <summary> + /// Direct StructureMap to build instances of type T, and look for concrete classes + /// marked with the [Pluggable] attribute that implement type T. + /// + /// This is the equivalent of calling BuildInstancesOf<T>() + /// </summary> + /// <typeparam name="PLUGINTYPE"></typeparam> + /// <returns></returns> + public CreatePluginFamilyExpression ForRequestedType<PLUGINTYPE>() + { + CreatePluginFamilyExpression expression = new CreatePluginFamilyExpression(typeof(PLUGINTYPE)); + addExpression(expression); + + return expression; + } + public IInstanceManager BuildInstanceManager() { ConfigurePluginGraph(_graph); @@ -72,57 +88,59 @@ /// <summary> /// Starts an instance definition of type T /// </summary> - /// <typeparam name="T"></typeparam> + /// <typeparam name="PLUGINTYPE"></typeparam> /// <returns></returns> - public InstanceExpression.InstanceTypeExpression AddInstanceOf<T>() + public InstanceExpression.InstanceTypeExpression AddInstanceOf<PLUGINTYPE>() { - InstanceExpression expression = new InstanceExpression(typeof (T)); + InstanceExpression expression = new InstanceExpression(typeof (PLUGINTYPE)); addExpression(expression); return expression.TypeExpression(); } + + /// <summary> /// Convenience method to start the definition of an instance of type T /// </summary> - /// <typeparam name="T"></typeparam> + /// <typeparam name="PLUGINTYPE"></typeparam> /// <returns></returns> - public static InstanceExpression.InstanceTypeExpression Instance<T>() + public static InstanceExpression.InstanceTypeExpression Instance<PLUGINTYPE>() { - InstanceExpression expression = new InstanceExpression(typeof (T)); + InstanceExpression expression = new InstanceExpression(typeof (PLUGINTYPE)); return expression.TypeExpression(); } /// <summary> /// Convenience method to register a prototype instance /// </summary> - /// <typeparam name="T"></typeparam> + /// <typeparam name="PLUGINTYPE"></typeparam> /// <param name="prototype"></param> /// <returns></returns> - public static PrototypeExpression<T> Prototype<T>(T prototype) + public static PrototypeExpression<PLUGINTYPE> Prototype<PLUGINTYPE>(PLUGINTYPE prototype) { - return new PrototypeExpression<T>(prototype); + return new PrototypeExpression<PLUGINTYPE>(prototype); } /// <summary> /// Convenience method to register a preconfigured instance of type T /// </summary> - /// <typeparam name="T"></typeparam> + /// <typeparam name="PLUGINTYPE"></typeparam> /// <param name="instance"></param> /// <returns></returns> - public static LiteralExpression<T> Object<T>(T instance) + public static LiteralExpression<PLUGINTYPE> Object<PLUGINTYPE>(PLUGINTYPE instance) { - return new LiteralExpression<T>(instance); + return new LiteralExpression<PLUGINTYPE>(instance); } /// <summary> /// Registers a preconfigured instance /// </summary> - /// <typeparam name="T"></typeparam> + /// <typeparam name="PLUGINTYPE"></typeparam> /// <param name="target"></param> /// <returns></returns> - public LiteralExpression<T> AddInstanceOf<T>(T target) + public LiteralExpression<PLUGINTYPE> AddInstanceOf<PLUGINTYPE>(PLUGINTYPE target) { - LiteralExpression<T> literal = new LiteralExpression<T>(target); + LiteralExpression<PLUGINTYPE> literal = new LiteralExpression<PLUGINTYPE>(target); addExpression(literal); return literal; @@ -131,12 +149,12 @@ /// <summary> /// Add a preconfigured instance as a Prototype /// </summary> - /// <typeparam name="T"></typeparam> + /// <typeparam name="PLUGINTYPE"></typeparam> /// <param name="prototype"></param> /// <returns></returns> - public PrototypeExpression<T> AddPrototypeInstanceOf<T>(T prototype) + public PrototypeExpression<PLUGINTYPE> AddPrototypeInstanceOf<PLUGINTYPE>(PLUGINTYPE prototype) { - PrototypeExpression<T> expression = new PrototypeExpression<T>(prototype); + PrototypeExpression<PLUGINTYPE> expression = new PrototypeExpression<PLUGINTYPE>(prototype); addExpression(expression); return expression; @@ -145,12 +163,12 @@ /// <summary> /// convenience method for a UserControl /// </summary> - /// <typeparam name="T"></typeparam> + /// <typeparam name="PLUGINTYPE"></typeparam> /// <param name="url"></param> /// <returns></returns> - public static UserControlExpression LoadUserControlFrom<T>(string url) + public static UserControlExpression LoadUserControlFrom<PLUGINTYPE>(string url) { - return new UserControlExpression(typeof (T), url); + return new UserControlExpression(typeof (PLUGINTYPE), url); } /// <summary> @@ -184,15 +202,21 @@ /// <summary> /// Registers a UserControl as an instance /// </summary> - /// <typeparam name="T"></typeparam> + /// <typeparam name="PLUGINTYPE"></typeparam> /// <param name="url"></param> /// <returns></returns> - public UserControlExpression LoadControlFromUrl<T>(string url) + public UserControlExpression LoadControlFromUrl<PLUGINTYPE>(string url) { - UserControlExpression expression = new UserControlExpression(typeof (T), url); + UserControlExpression expression = new UserControlExpression(typeof (PLUGINTYPE), url); addExpression(expression); return expression; } + + public static ConstructorExpression<PLUGINTYPE> ConstructedBy<PLUGINTYPE> + (BuildObjectDelegate<PLUGINTYPE> builder) + { + return new ConstructorExpression<PLUGINTYPE>(builder); + } } } \ No newline at end of file Added: trunk/Source/StructureMap/ConstructorMemento.cs =================================================================== --- trunk/Source/StructureMap/ConstructorMemento.cs (rev 0) +++ trunk/Source/StructureMap/ConstructorMemento.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -0,0 +1,40 @@ +using System; + +namespace StructureMap +{ + public delegate PLUGINTYPE BuildObjectDelegate<PLUGINTYPE>(); + + public class ConstructorMemento<PLUGINTYPE> : MemoryInstanceMemento + { + private BuildObjectDelegate<PLUGINTYPE> _builder; + + + public ConstructorMemento() + { + } + + public ConstructorMemento(string instanceKey, BuildObjectDelegate<PLUGINTYPE> builder) + : base(instanceKey, instanceKey) + { + _builder = builder; + } + + public ConstructorMemento(BuildObjectDelegate<PLUGINTYPE> builder) + : this(Guid.NewGuid().ToString(), builder) + { + + } + + public override object Build(IInstanceCreator creator) + { + return _builder(); + } + + + public BuildObjectDelegate<PLUGINTYPE> Builder + { + get { return _builder; } + set { _builder = value; } + } + } +} Modified: trunk/Source/StructureMap/Graph/Plugin.cs =================================================================== --- trunk/Source/StructureMap/Graph/Plugin.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/Graph/Plugin.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -13,6 +13,18 @@ { #region static + public static Plugin CreateAutofilledPlugin(Type concreteType) + { + string pluginKey = Guid.NewGuid().ToString(); + Plugin plugin = Plugin.CreateExplicitPlugin(concreteType, pluginKey, string.Empty); + if (!plugin.CanBeAutoFilled) + { + throw new StructureMapException(231); + } + + return plugin; + } + /// <summary> /// Finds an array of Plugin objects for a given PluginType in an Assembly object /// by searching for all exported types marked with [Pluggable] that can be cast @@ -428,5 +440,14 @@ throw new StructureMapException(302, typeof (T).FullName, _pluggedType.FullName); } + + public void AddToSource(MementoSource source) + { + InstanceMemento memento = CreateImplicitMemento(); + if (memento != null) + { + source.AddExternalMemento(memento); + } + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/PluginCollection.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginCollection.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/Graph/PluginCollection.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -22,6 +22,17 @@ get { return _plugins.Values; } } + public Plugin[] All + { + get + { + Plugin[] returnValue = new Plugin[_plugins.Count]; + _plugins.Values.CopyTo(returnValue, 0); + + return returnValue; + } + } + public void Add(TypePath path, string concreteKey) { Plugin plugin = new Plugin(path, concreteKey); @@ -61,12 +72,9 @@ throw new StructureMapException(114, plugin.PluggedType.FullName, _family.PluginTypeName); } - InstanceMemento memento = plugin.CreateImplicitMemento(); - if (memento != null) - { - _family.Source.AddExternalMemento(memento); - } + plugin.AddToSource(_family.Source); + _plugins.Add(plugin.ConcreteKey, plugin); } Modified: trunk/Source/StructureMap/Graph/PluginFamily.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginFamily.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/Graph/PluginFamily.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -16,19 +16,14 @@ public static PluginFamily CreateAutoFilledPluginFamily(Type pluginType) { - Plugin plugin = Plugin.CreateExplicitPlugin(pluginType, CONCRETE_KEY, string.Empty); - if (!plugin.CanBeAutoFilled) - { - throw new StructureMapException(231); - } + Plugin plugin = Plugin.CreateAutofilledPlugin(pluginType); PluginFamily family = new PluginFamily(pluginType); family.DefinitionSource = DefinitionSource.Implicit; family.Plugins.Add(plugin); + family.DefaultInstanceKey = plugin.ConcreteKey; - family.DefaultInstanceKey = CONCRETE_KEY; - return family; } Modified: trunk/Source/StructureMap/IInstanceFactory.cs =================================================================== --- trunk/Source/StructureMap/IInstanceFactory.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/IInstanceFactory.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -69,5 +69,8 @@ /// </summary> /// <returns></returns> IList GetAllInstances(); + + void AddInstance(InstanceMemento memento); + InstanceMemento AddType<T>(); } } \ No newline at end of file Modified: trunk/Source/StructureMap/IInstanceManager.cs =================================================================== --- trunk/Source/StructureMap/IInstanceManager.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/IInstanceManager.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -8,7 +8,7 @@ T CreateInstance<T>(string instanceKey); T CreateInstance<T>(); T FillDependencies<T>(); - void Inject<T>(T instance); + void InjectStub<T>(T instance); IList<T> GetAllInstances<T>(); void SetDefaultsToProfile(string profile); Modified: trunk/Source/StructureMap/InstanceBuilder.cs =================================================================== --- trunk/Source/StructureMap/InstanceBuilder.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/InstanceBuilder.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -1,3 +1,6 @@ +using System; +using StructureMap.Graph; + namespace StructureMap { /// <summary> @@ -26,5 +29,11 @@ { get { return _manager; } } + + public bool IsType(Type type) + { + Type plugged = Type.GetType(PluggedType); + return plugged.Equals(type); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/InstanceFactory.cs =================================================================== --- trunk/Source/StructureMap/InstanceFactory.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/InstanceFactory.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Reflection; @@ -15,15 +16,14 @@ public class InstanceFactory : IInstanceFactory, IInstanceCreator { private Type _pluginType; - private string _assemblyName; - private HybridDictionary _instanceBuilders; + private Dictionary<string, InstanceBuilder> _instanceBuilders; private MementoSource _source; #region constructor functions private InstanceFactory() { - _instanceBuilders = new HybridDictionary(); + _instanceBuilders = new Dictionary<string, InstanceBuilder>(); _source = new MemoryMementoSource(); } @@ -42,8 +42,8 @@ try { determineMementoSource(family); - setPluginType(family.PluginType); - processPlugins(family.Plugins); + _pluginType = family.PluginType; + processPlugins(family.Plugins.All); determineDefaultKey(family, failOnException); } catch (Exception e) @@ -52,6 +52,7 @@ } } + private void determineMementoSource(PluginFamily family) { if (family.Source == null) @@ -102,13 +103,6 @@ } } - - private void setPluginType(Type PluginType) - { - _pluginType = PluginType; - _assemblyName = Guid.NewGuid().ToString().Replace(".", "") + "InstanceBuilderAssembly"; - } - #endregion /// <summary> @@ -125,21 +119,19 @@ #region create instance builders - private void processPlugins(PluginCollection plugins) + private void processPlugins(Plugin[] plugins) { - _instanceBuilders.Clear(); - Assembly assembly = createInstanceBuilderAssembly(plugins); - foreach (Plugin plugin in plugins) { addPlugin(assembly, plugin); } } - private Assembly createInstanceBuilderAssembly(PluginCollection plugins) + private Assembly createInstanceBuilderAssembly(Plugin[] plugins) { - InstanceBuilderAssembly builderAssembly = new InstanceBuilderAssembly(_assemblyName, PluginType); + string assemblyName = Guid.NewGuid().ToString().Replace(".", "") + "InstanceBuilderAssembly"; + InstanceBuilderAssembly builderAssembly = new InstanceBuilderAssembly(assemblyName, PluginType); foreach (Plugin plugin in plugins) { @@ -212,7 +204,7 @@ public object BuildInstance(InstanceMemento memento) { - if (!_instanceBuilders.Contains(memento.ConcreteKey)) + if (!_instanceBuilders.ContainsKey(memento.ConcreteKey)) { throw new StructureMapException( 201, memento.ConcreteKey, memento.InstanceKey, PluginType.FullName); @@ -338,5 +330,30 @@ return list; } + + public void AddInstance(InstanceMemento memento) + { + _source.AddExternalMemento(memento); + } + + + public InstanceMemento AddType<T>() + { + Type pluggedType = typeof (T); + foreach (KeyValuePair<string, InstanceBuilder> pair in _instanceBuilders) + { + InstanceBuilder builder = pair.Value; + if (builder.IsType(pluggedType)) + { + return new MemoryInstanceMemento(builder.ConcreteTypeKey, builder.ConcreteTypeKey); + } + } + + Plugin plugin = Plugin.CreateImplicitPlugin(typeof (T)); + processPlugins(new Plugin[]{plugin}); + plugin.AddToSource(_source); + + return plugin.CreateImplicitMemento(); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/InstanceManager.cs =================================================================== --- trunk/Source/StructureMap/InstanceManager.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/InstanceManager.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -1,7 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; -using NMock; +using StructureMap.Configuration.DSL; using StructureMap.Exceptions; using StructureMap.Graph; using StructureMap.Interceptors; @@ -14,7 +14,6 @@ public class InstanceManager : IInstanceManager, IEnumerable { private Dictionary<Type, IInstanceFactory> _factories; - private Dictionary<Type, InstanceFactory> _filledTypeFactories; private bool _failOnException = true; private GenericsPluginGraph _genericsGraph; private InstanceDefaultManager _defaultManager; @@ -25,7 +24,6 @@ public InstanceManager() { _factories = new Dictionary<Type, IInstanceFactory>(); - _filledTypeFactories = new Dictionary<Type, InstanceFactory>(); _genericsGraph = new GenericsPluginGraph(); } @@ -325,7 +323,12 @@ throw new StructureMapException(230); } - InstanceFactory factory = getFilledTypeFactory(type); + IInstanceFactory factory = getOrCreateFactory(type, delegate(Type t) + { + PluginFamily family = + PluginFamily.CreateAutoFilledPluginFamily(t); + return new InstanceFactory(family, true); + }); return factory.GetInstance(); } @@ -334,118 +337,27 @@ return (T) FillDependencies(typeof (T)); } - private InstanceFactory getFilledTypeFactory(Type type) + private delegate InstanceFactory CreateFactoryDelegate(Type type); + + private IInstanceFactory getOrCreateFactory(Type type, CreateFactoryDelegate createFactory) { - if (!_filledTypeFactories.ContainsKey(type)) + if (!_factories.ContainsKey(type)) { lock (this) { - if (!_filledTypeFactories.ContainsKey(type)) + if (!_factories.ContainsKey(type)) { - PluginFamily family = PluginFamily.CreateAutoFilledPluginFamily(type); - InstanceFactory factory = new InstanceFactory(family, true); + InstanceFactory factory = createFactory(type); factory.SetInstanceManager(this); - _filledTypeFactories.Add(type, factory); + _factories.Add(type, factory); } } } - return _filledTypeFactories[type]; + return _factories[type]; } - #region mocking - /// <summary> - /// When called, returns an NMock.IMock instance for the TargetType. Until UnMocked, calling - /// GetInstance(Type TargetType) will return the MockInstance member of the IMock - /// </summary> - /// <param name="TargetType"></param> - /// <returns></returns> - public IMock Mock(Type TargetType) - { - if (IsMocked(TargetType)) - { - string msg = string.Format("The Type {0} is already mocked", TargetType.AssemblyQualifiedName); - throw new InvalidOperationException(msg); - } - - IInstanceFactory factory = this[TargetType]; - MockInstanceFactory mockFactory = new MockInstanceFactory(factory); - IMock returnValue = mockFactory.GetMock(); - - lock (this) - { - this[TargetType] = mockFactory; - } - - return returnValue; - } - - /// <summary> - /// Is the specified TargetType currently setup as an IMock - /// </summary> - /// <param name="TargetType"></param> - /// <returns></returns> - public bool IsMocked(Type TargetType) - { - return isInstanceFamilyMocked(this[TargetType]); - } - - private static bool isInstanceFamilyMocked(IInstanceFactory instanceFactory) - { - bool returnValue = false; - - InstanceFactoryInterceptor interceptor = instanceFactory as InstanceFactoryInterceptor; - if (interceptor != null) - { - returnValue = interceptor.IsMockedOrStubbed; - } - - return returnValue; - } - - /// <summary> - /// Release the NMock behavior of TargetType - /// </summary> - /// <param name="TargetType"></param> - public void UnMock(Type TargetType) - { - if (IsMocked(TargetType)) - { - InstanceFactoryInterceptor instanceFactory = (InstanceFactoryInterceptor) this[TargetType]; - IInstanceFactory innerFactory = instanceFactory.InnerInstanceFactory; - lock (this) - { - this[TargetType] = innerFactory; - } - } - } - - /// <summary> - /// Calls UnMock() on all IInstanceFactory's - /// </summary> - public void UnMockAll() - { - ArrayList typeList = new ArrayList(); - lock (this) - { - foreach (IInstanceFactory factory in _factories.Values) - { - if (isInstanceFamilyMocked(factory)) - { - typeList.Add(factory.PluginType); - } - } - - - foreach (Type type in typeList) - { - UnMock(type); - } - } - } - - /// <summary> /// Sets up the InstanceManager to return the object in the "stub" argument anytime /// any instance of the PluginType is requested /// </summary> @@ -459,21 +371,15 @@ stub.GetType().FullName); } - IInstanceFactory innerFactory = this[pluginType]; - StubbedInstanceFactory stubbedFactory = new StubbedInstanceFactory(innerFactory, stub); - lock (this) - { - this[pluginType] = stubbedFactory; - } + LiteralMemento memento = new LiteralMemento(stub); + this[pluginType].SetDefault(memento); } - public void Inject<T>(T instance) + public void InjectStub<T>(T instance) { InjectStub(typeof (T), instance); } - #endregion - public IEnumerator GetEnumerator() { return _factories.Values.GetEnumerator(); @@ -503,5 +409,31 @@ Profile defaultProfile = _defaultManager.CalculateDefaults(machineName, profile); SetDefaults(defaultProfile); } + + public void AddInstance<T>(InstanceMemento memento) + { + IInstanceFactory factory = getOrCreateFactory(typeof (T), createFactory); + factory.AddInstance(memento); + } + + public void AddInstance<PLUGINTYPE, CONCRETETYPE>() + { + IInstanceFactory factory = getOrCreateFactory(typeof(PLUGINTYPE), createFactory); + InstanceMemento memento = factory.AddType<CONCRETETYPE>(); + factory.AddInstance(memento); + } + + private InstanceFactory createFactory(Type pluggedType) + { + PluginFamily family = new PluginFamily(pluggedType); + return new InstanceFactory(family, true); + } + + public void AddDefaultInstance<PLUGINTYPE, CONCRETETYPE>() + { + IInstanceFactory factory = getOrCreateFactory(typeof (PLUGINTYPE), createFactory); + InstanceMemento memento = factory.AddType<CONCRETETYPE>(); + factory.SetDefault(memento); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Interceptors/InstanceFactoryInterceptor.cs =================================================================== --- trunk/Source/StructureMap/Interceptors/InstanceFactoryInterceptor.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/Interceptors/InstanceFactoryInterceptor.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -15,10 +15,6 @@ private IInstanceFactory _innerInstanceFactory; - public InstanceFactoryInterceptor() - { - } - public virtual IInstanceFactory InnerInstanceFactory { get { return _innerInstanceFactory; } @@ -112,6 +108,16 @@ return InnerInstanceFactory.GetAllInstances(); } + public void AddInstance(InstanceMemento memento) + { + InnerInstanceFactory.AddInstance(memento); + } + + public InstanceMemento AddType<T>() + { + return InnerInstanceFactory.AddType<T>(); + } + /// <summary> /// Declares whether or not the interceptor creates a stubbed or mocked version of the PluginType /// </summary> Modified: trunk/Source/StructureMap/MemoryInstanceMemento.cs =================================================================== --- trunk/Source/StructureMap/MemoryInstanceMemento.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/MemoryInstanceMemento.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -1,8 +1,16 @@ using System.Collections; using System.Collections.Specialized; +using StructureMap.Graph; namespace StructureMap { + public class GenericMemento<T> : MemoryInstanceMemento + { + public GenericMemento(string instanceKey) + : base(Plugin.CreateImplicitPlugin(typeof(T)).ConcreteKey, instanceKey) + {} + } + /// <summary> /// An in-memory implementation of InstanceMemento. /// </summary> @@ -59,6 +67,7 @@ { } + /// <summary> /// Constructs a MemoryInstanceMemento with properties /// </summary> Deleted: trunk/Source/StructureMap/MockInstanceFactory.cs =================================================================== --- trunk/Source/StructureMap/MockInstanceFactory.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/MockInstanceFactory.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -1,72 +0,0 @@ -using NMock; -using StructureMap.Interceptors; - -namespace StructureMap -{ - /// <summary> - /// Implementation of IInstanceFactory that uses NMock internally to create instances of the - /// PluginType - /// </summary> - public class MockInstanceFactory : InstanceFactoryInterceptor - { - private IMock _mockType; - - /// <summary> - /// Creates a MockInstanceFactory that wraps and intercepts calls to the innerFactory - /// </summary> - /// <param name="innerFactory"></param> - public MockInstanceFactory(IInstanceFactory innerFactory) - { - InnerInstanceFactory = innerFactory; - _mockType = new DynamicMock(innerFactory.PluginType); - } - - /// <summary> - /// Returns "new DyanamicProxy(this.PluginType) as IMock" - /// </summary> - /// <returns></returns> - public IMock GetMock() - { - return _mockType; - } - - /// <summary> - /// See <cref>IInstanceFactory</cref> - /// </summary> - /// <param name="InstanceKey"></param> - /// <returns></returns> - public override object GetInstance(string InstanceKey) - { - return _mockType.MockInstance; - } - - /// <summary> - /// See <cref>IInstanceFactory</cref> - /// </summary> - /// <param name="Memento"></param> - /// <returns></returns> - public override object GetInstance(InstanceMemento Memento) - { - return _mockType.MockInstance; - } - - /// <summary> - /// See <cref>IInstanceFactory</cref> - /// </summary> - /// <returns></returns> - public override object GetInstance() - { - return _mockType.MockInstance; - } - - public override bool IsMockedOrStubbed - { - get { return true; } - } - - public override object Clone() - { - return MemberwiseClone(); - } - } -} \ No newline at end of file Modified: trunk/Source/StructureMap/ObjectFactory.cs =================================================================== --- trunk/Source/StructureMap/ObjectFactory.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/ObjectFactory.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Security.Permissions; using System.Text; -using NMock; +using StructureMap.Configuration.DSL; using StructureMap.Graph; namespace StructureMap @@ -109,14 +109,9 @@ { lock (_lockObject) { - manager.UnMockAll(); Profile = string.Empty; } } - catch (StructureMapException) - { - throw; - } catch (TypeInitializationException ex) { if (ex.InnerException is StructureMapException) @@ -286,62 +281,99 @@ return (T) _manager.FillDependencies(typeof (T)); } - #region Mocking - /// <summary> - /// When called, returns an NMock.IMock instance for the TargetType. Until UnMocked, calling - /// GetInstance(Type TargetType) will return the MockInstance member of the IMock + /// Sets up StructureMap to return the object in the "stub" argument anytime + /// any instance of the PluginType is requested /// </summary> - /// <param name="TargetType"></param> - /// <returns></returns> - public static IMock Mock(Type TargetType) + /// <param name="pluginType"></param> + /// <param name="stub"></param> + public static void InjectStub(Type pluginType, object stub) { - return manager.Mock(TargetType); + manager.InjectStub(pluginType, stub); } /// <summary> - /// Sets up the internal InstanceManager to return the object in the "stub" argument anytime + /// Sets up StructureMap to return the object in the "stub" argument anytime /// any instance of the PluginType is requested /// </summary> /// <param name="targetType"></param> /// <param name="stub"></param> - public static void InjectStub(Type targetType, object stub) + public static void InjectStub<PLUGINTYPE>(PLUGINTYPE stub) { - manager.InjectStub(targetType, stub); + manager.InjectStub(typeof (PLUGINTYPE), stub); } + + public static string WhatDoIHave() + { + StringBuilder sb = new StringBuilder(); + + foreach (IInstanceFactory factory in manager) + { + sb.AppendFormat("PluginType {0}, Default: {1}\r\n", factory.PluginType.AssemblyQualifiedName, + factory.DefaultInstanceKey); + } + + return sb.ToString(); + } + /// <summary> - /// Is the specified TargetType currently setup as an IMock + /// Sets the default instance of PLUGINTYPE to the object in the instance argument /// </summary> - /// <param name="TargetType"></param> - /// <returns></returns> - public static bool IsMocked(Type TargetType) + /// <typeparam name="PLUGINTYPE"></typeparam> + /// <param name="instance"></param> + public static void Inject<PLUGINTYPE>(PLUGINTYPE instance) { - return manager.IsMocked(TargetType); + LiteralMemento memento = new LiteralMemento(instance); + manager.AddInstance<PLUGINTYPE>(memento); + manager.SetDefault(typeof (PLUGINTYPE), memento); } /// <summary> - /// Release the NMock behavior of TargetType + /// Injects a new instance of PLUGINTYPE by name. /// </summary> - /// <param name="TargetType"></param> - public static void UnMock(Type TargetType) + /// <typeparam name="PLUGINTYPE"></typeparam> + /// <param name="instance"></param> + /// <param name="instanceKey"></param> + public static void InjectByName<PLUGINTYPE>(PLUGINTYPE instance, string instanceKey) { - manager.UnMock(TargetType); + LiteralMemento memento = new LiteralMemento(instance).Named(instanceKey); + manager.AddInstance<PLUGINTYPE>(memento); } - #endregion + /// <summary> + /// Injects a new instance of CONCRETETYPE to PLUGINTYPE by name. + /// </summary> + /// <typeparam name="PLUGINTYPE"></typeparam> + /// <param name="instance"></param> + /// <param name="instanceKey"></param> + public static void InjectByName<PLUGINTYPE, CONCRETETYPE>(string instanceKey) + { + manager.AddInstance<PLUGINTYPE, CONCRETETYPE>(); + GenericMemento<CONCRETETYPE> memento = new GenericMemento<CONCRETETYPE>(instanceKey); + manager.AddInstance<PLUGINTYPE>(memento); + } - public static string WhatDoIHave() + /// <summary> + /// StructureMap will return an instance of CONCRETETYPE whenever + /// a PLUGINTYPE is requested + /// </summary> + /// <typeparam name="PLUGINTYPE"></typeparam> + /// <typeparam name="CONCRETETYPE"></typeparam> + public static void InjectDefaultType<PLUGINTYPE, CONCRETETYPE>() where CONCRETETYPE : PLUGINTYPE { - StringBuilder sb = new StringBuilder(); + manager.AddDefaultInstance<PLUGINTYPE, CONCRETETYPE>(); + } - foreach (IInstanceFactory factory in manager) - { - sb.AppendFormat("PluginType {0}, Default: {1}\r\n", factory.PluginType.AssemblyQualifiedName, - factory.DefaultInstanceKey); - } - - return sb.ToString(); + /// <summary> + /// Adds a new CONCRETETYPE to StructureMap so that an instance of CONCRETETYPE + /// will be returned from a call to ObjectFactory.GetAllInstances<PLUGINTYPE>() + /// </summary> + /// <typeparam name="PLUGINTYPE"></typeparam> + /// <typeparam name="CONCRETETYPE"></typeparam> + public static void AddType<PLUGINTYPE, CONCRETETYPE>() where CONCRETETYPE : PLUGINTYPE + { + manager.AddInstance<PLUGINTYPE, CONCRETETYPE>(); } } } \ No newline at end of file Modified: trunk/Source/StructureMap/StructureMap.csproj =================================================================== --- trunk/Source/StructureMap/StructureMap.csproj 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/StructureMap.csproj 2007-12-14 11:16:38 UTC (rev 49) @@ -96,10 +96,6 @@ <ErrorReport>prompt</ErrorReport> </PropertyGroup> <ItemGroup> - <Reference Include="nmock"> - <Name>nmock</Name> - <HintPath>..\..\bin\nmock.dll</HintPath> - </Reference> <Reference Include="System"> <Name>System</Name> </Reference> @@ -214,6 +210,7 @@ <SubType>Code</SubType> </Compile> <Compile Include="Configuration\DSL\ChildInstanceExpression.cs" /> + <Compile Include="Configuration\DSL\ConstructorExpression.cs" /> <Compile Include="Configuration\DSL\CreatePluginFamilyExpression.cs" /> <Compile Include="Configuration\DSL\ExpressionValidator.cs" /> <Compile Include="Configuration\DSL\IExpression.cs" /> @@ -335,6 +332,7 @@ <Compile Include="Configuration\XmlConstants.cs"> <SubType>Code</SubType> </Compile> + <Compile Include="ConstructorMemento.cs" /> <Compile Include="DeploymentTasks\DeploymentConfiguration.cs"> <SubType>Code</SubType> </Compile> @@ -498,9 +496,6 @@ <Compile Include="MemoryInstanceMemento.cs"> <SubType>Code</SubType> </Compile> - <Compile Include="MockInstanceFactory.cs"> - <SubType>Code</SubType> - </Compile> <Compile Include="ObjectFactory.cs"> <SubType>Code</SubType> </Compile> @@ -556,9 +551,6 @@ <SubType>Code</SubType> </Compile> <Compile Include="StructureMapConfiguration.cs" /> - <Compile Include="StubbedInstanceFactory.cs"> - <SubType>Code</SubType> - </Compile> <Compile Include="Verification\IStartUp.cs" /> <Compile Include="Verification\PluginGraphConsoleWriter.cs"> <SubType>Code</SubType> Modified: trunk/Source/StructureMap/StructureMapException.resx =================================================================== --- trunk/Source/StructureMap/StructureMapException.resx 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/StructureMapException.resx 2007-12-14 11:16:38 UTC (rev 49) @@ -249,4 +249,7 @@ <data name="105" xml:space="preserve"> <value>The <{0}> section could not be loaded from the application configuration file.</value> </data> + <data name="306" xml:space="preserve"> + <value>The configured BuilderDelegate of type {0} does not match the PluginFamily type {1}</value> + </data> </root> \ No newline at end of file Deleted: trunk/Source/StructureMap/StubbedInstanceFactory.cs =================================================================== --- trunk/Source/StructureMap/StubbedInstanceFactory.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap/StubbedInstanceFactory.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -1,59 +0,0 @@ -using StructureMap.Interceptors; - -namespace StructureMap -{ - /// <summary> - /// Decorator that intercepts a call to create a PluginType and returns a - /// static mock or stub. Used when ObjectFactory.InjectStub(Type, object) is called. - /// </summary> - public class StubbedInstanceFactory : InstanceFactoryInterceptor - { - private readonly object _stub; - - public StubbedInstanceFactory(IInstanceFactory innerFactory, object stub) : base() - { - InnerInstanceFactory = innerFactory; - _stub = stub; - } - - /// <summary> - /// Creates an object instance for the InstanceKey - /// </summary> - /// <param name="InstanceKey">The named instance</param> - /// <returns></returns> - public override object GetInstance(string InstanceKey) - { - return _stub; - } - - /// <summary> - /// Creates an object instance directly from the Memento - /// </summary> - /// <param name="Memento">A representation of an object instance</param> - /// <returns></returns> - public override object GetInstance(InstanceMemento Memento) - { - return _stub; - } - - /// <summary> - /// Creates a new object instance of the default instance memento - /// </summary> - /// <returns></returns> - public override object GetInstance() - { - return _stub; - } - - - public override bool IsMockedOrStubbed - { - get { return true; } - } - - public override object Clone() - { - return MemberwiseClone(); - } - } -} \ No newline at end of file Added: trunk/Source/StructureMap.Testing/Configuration/DSL/ConstructorExpressionTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Configuration/DSL/ConstructorExpressionTester.cs (rev 0) +++ trunk/Source/StructureMap.Testing/Configuration/DSL/ConstructorExpressionTester.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -0,0 +1,100 @@ +using NUnit.Framework; +using Rhino.Mocks; +using StructureMap.Configuration.DSL; +using StructureMap.Testing.Container; + +namespace StructureMap.Testing.Configuration.DSL +{ + [TestFixture] + public class ConstructorExpressionTester + { + [SetUp] + public void SetUp() + { + StructureMapConfiguration.ResetAll(); + ObjectFactory.Reset(); + } + + public interface Abstraction { } + + public class Concretion : Abstraction { } + + [Test] + public void ConstructSomething() + { + Concretion concretion = new Concretion(); + + Registry registry = new Registry(); + registry.ForRequestedType<Abstraction>().TheDefaultIs( + Registry.ConstructedBy<Abstraction>(delegate { return concretion; }) + ); + + IInstanceManager manager = registry.BuildInstanceManager(); + Assert.AreSame(concretion, manager.CreateInstance<Abstraction>()); + } + + [Test] + public void ConstructSomethingNotByDefault() + { + Concretion concretion = new Concretion(); + + Registry registry = new Registry(); + registry.ForRequestedType<Abstraction>().AddInstance( + Registry.ConstructedBy<Abstraction>(delegate { return concretion; }) + ); + + + IInstanceManager manager = registry.BuildInstanceManager(); + + Abstraction actual = manager.GetAllInstances<Abstraction>()[0]; + Assert.AreSame(concretion, actual); + + } + + [Test] + public void ConstructSomethingByName() + { + Concretion concretion1 = new Concretion(); + Concretion concretion2 = new Concretion(); + + Registry registry = new Registry(); + registry.ForRequestedType<Abstraction>().AddInstance( + Registry.ConstructedBy<Abstraction>(delegate { return concretion1; }).WithName("One") + ); + + registry.ForRequestedType<Abstraction>().AddInstance( + Registry.ConstructedBy<Abstraction>(delegate { return concretion2; }).WithName("Two") + ); + + IInstanceManager manager = registry.BuildInstanceManager(); + + Assert.AreSame(concretion1, manager.CreateInstance<Abstraction>("One")); + Assert.AreSame(concretion2, manager.CreateInstance<Abstraction>("Two")); + + } + + [Test] + public void AddTwoConstructorsConsecutively() + { + Concretion concretion1 = new Concretion(); + Concretion concretion2 = new Concretion(); + + Registry registry = new Registry(); + registry.ForRequestedType<Abstraction>() + .AddInstance( + Registry.ConstructedBy<Abstraction>(delegate { return concretion1; }).WithName("One") + ) + .AddInstance( + Registry.ConstructedBy<Abstraction>(delegate { return concretion2; }).WithName("Two") + ); + + IInstanceManager manager = registry.BuildInstanceManager(); + + Assert.AreSame(concretion1, manager.CreateInstance<Abstraction>("One")); + Assert.AreSame(concretion2, manager.CreateInstance<Abstraction>("Two")); + + } + } + + +} Modified: trunk/Source/StructureMap.Testing/Configuration/DSL/RegistryIntegratedTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Configuration/DSL/RegistryIntegratedTester.cs 2007-07-27 13:43:55 UTC (rev 48) +++ trunk/Source/StructureMap.Testing/Configuration/DSL/RegistryIntegratedTester.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -82,5 +82,6 @@ Assert.Contains("Brown", colors); Assert.Contains("Black", colors); } + } } \ No newline at end of file Added: trunk/Source/StructureMap.Testing/ConstructorMementoTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/ConstructorMementoTester.cs (rev 0) +++ trunk/Source/StructureMap.Testing/ConstructorMementoTester.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -0,0 +1,23 @@ +using NUnit.Framework; +using Rhino.Mocks; + +namespace StructureMap.Testing +{ + [TestFixture] + public class ConstructorMementoTester + { + [SetUp] + public void SetUp() + { + } + + [Test] + public void Construct() + { + ConstructorMemento<string> memento = new ConstructorMemento<string>("A", delegate { return "Hello"; }); + Assert.AreEqual("A", memento.InstanceKey); + string actual = (string) memento.Build(null); + Assert.AreEqual("Hello", actual); + } + } +} Added: trunk/Source/StructureMap.Testing/Container/DynamicInjectionTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Container/DynamicInjectionTester.cs (rev 0) +++ trunk/Source/StructureMap.Testing/Container/DynamicInjectionTester.cs 2007-12-14 11:16:38 UTC (rev 49) @@ -0,0 +1,239 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework; +using Rhino.Mocks; +using StructureMap.Configuration.DSL; +using StructureMap.Graph; +using StructureMap.Interceptors; +using StructureMap.Testing.Widget3; + +namespace StructureMap.Testing.Container +{ + [TestFixture] + public class DynamicInjectionTester + { + private IService _red = new ColorService("Red"); + private IService _blue = new ColorService("Blue"); + private IService _orange = new ColorService("Orange"); + + [SetUp] + public void SetUp() + { + ObjectFactory.ReInitialize(); + StructureMapConfiguration.ResetAll(); + } + + [Test] + public void CanAddMementosDirectlyToAnInstanceFactory() + { + InstanceFactory factory = ObjectMother.Factory<IService>(); + + factory.AddInstance(new LiteralMemento(_red).Named("Red")); + factory.AddInstance(new LiteralMemento(_blue).Named("Blue")); + + Assert.AreSame(_red, factory.GetInstance("Red")); + Assert.AreSame(_blue, factory.GetInstance("Blue")); + } + + [Test] + public void NowOverwriteAPreviouslyAttachedMemento() + { + InstanceFactory factory = ObjectMother.Factory<IService>(); + + factory.AddInstance(new LiteralMemento(_red).Named("Red")); + factory.AddInstance(new LiteralMemento(_blue).Named("Blue")); + + // Replace Blue + factory.AddInstance(new LiteralMemento(_orange).Named("Blue")); + + Assert.AreSame(_orange, factory.GetInstance("Blue")); + } + + [Test] + public void AddInstanceWithInstanceFactoryInterceptor() + { + InstanceFactoryInterceptor interceptor = new FakeInstanceFactoryInterceptor(); + + InstanceFactory factory = ObjectMother.Factory<IService>(); + interceptor.InnerInstanceFactory = factory; + + interceptor.AddInstance(new LiteralMemento(_red).Named("Red")); + interceptor.AddInstance(new LiteralMemento(_blue).Named("Blue")); + + Assert.AreSame(_red, interceptor.GetInstance("Red")); + Assert.AreSame(_blue, interceptor.GetInstance("Blue")); + } + + [Test] + public void AddInstanceToInstanceManagerWhenTheInstanceFactoryDoesNotExist() + { + InstanceManager manager = new InstanceManager(); + manager.AddInstance<IService>(new LiteralMemento(_red).Named("Red")); + manager.AddInstance<IService>(new LiteralMemento(_blue).Named("Blue")); + + Assert.AreSame(_red, manager.CreateInstance(typeof(IService), "Red")); + Assert.AreSame(_blue, manager.CreateInstance(typeof(IService), "Blue")); + + } + + [Test] + public void AddInstanceFromObjectFactory() + { + SomethingOne one = new SomethingOne(); + ObjectFactory.Inject<ISomething>(one); + + Assert.AreSame(one, ObjectFactory.GetInstance<ISomething>()); + } + + [Test] + public void OverwriteInstanceFromObjectFactory() + { + SomethingOne one = new SomethingOne(); + SomethingOne two = new SomethingOne(); + ObjectFactory.Inject<ISomething>(one); + ObjectFactory.Inject<ISomething>(two); + + Assert.AreSame(two, ObjectFactory.GetInstance<ISomething>()); + } + + [Test] + public void AddNamedInstanceToobjectFactory() + { + SomethingOne one = new SomethingOne(); + SomethingOne two = new SomethingOne(); + + ObjectFactory.InjectByName<ISomething>(one, "One"); + ObjectFactory.InjectByName<ISomething>(two, "Two"); + + + Assert.AreSame(one, ObjectFactory.GetNamedInstance<ISomething>("One")); + Assert.AreSame(two, ObjectFactory.GetNamedInstance<ISomething>("Two")); + } + + [Test] + public void AddNamedInstanceByType() + { + ObjectFactory.InjectByName<ISomething, SomethingOne>("One"); + ObjectFactory.InjectByName<ISomething, SomethingTwo>("Two"); + + Assert.IsInstanceOfType(typeof(SomethingOne), ObjectFactory.GetNamedInstance<ISomething>("One")); + Assert.IsInstanceOfType(typeof(SomethingTwo), ObjectFactory.GetNamedInstance<ISomething>("Two")); + } + + [Test] + public void OverwriteInstanceAndDontBlowUp() + { + ObjectFactory.InjectByName<ISomething, SomethingOne>("One"); + ObjectFactory.InjectByName<ISomething, SomethingTwo>("One"); + + Assert.IsInstanceOfType(typeof(SomethingTwo), ObjectFactory.GetNamedInstance<ISomething>("One")); + } + + [Test] + public void JustAddATypeWithNoNameAndDefault() + { + ObjectFactory.InjectDefaultType<ISomething, SomethingOne>(); + Assert.IsInstanceOfType(typeof(SomethingOne), ObjectFactory.GetInstance<ISomething>()); + } + + [Test] +... [truncated message content] |
From: <jer...@us...> - 2008-02-12 15:23:19
|
Revision: 64 http://structuremap.svn.sourceforge.net/structuremap/?rev=64&view=rev Author: jeremydmiller Date: 2008-02-12 07:23:15 -0800 (Tue, 12 Feb 2008) Log Message: ----------- using DynamicMocks by default in the AutoMocking Modified Paths: -------------- trunk/Source/StructureMap.AutoMocking/RhinoAutoMocker.cs trunk/Source/StructureMap.AutoMocking/RhinoMocksServiceLocator.cs trunk/Source/StructureMap.Testing/AutoMocking/RhinoAutoMockerTester.cs Modified: trunk/Source/StructureMap.AutoMocking/RhinoAutoMocker.cs =================================================================== --- trunk/Source/StructureMap.AutoMocking/RhinoAutoMocker.cs 2008-02-09 16:10:55 UTC (rev 63) +++ trunk/Source/StructureMap.AutoMocking/RhinoAutoMocker.cs 2008-02-12 15:23:15 UTC (rev 64) @@ -79,6 +79,15 @@ { _manager.InjectStub<T>(stub); } + + // So that Aaron Jensen can use his concrete HubService object + // Construct whatever T is with all mocks, and make sure that the + // ClassUnderTest gets built with a concrete T + public void UseConcreteClassFor<T>() + { + T concreteClass = _manager.FillDependencies<T>(); + _manager.InjectStub(concreteClass); + } } Modified: trunk/Source/StructureMap.AutoMocking/RhinoMocksServiceLocator.cs =================================================================== --- trunk/Source/StructureMap.AutoMocking/RhinoMocksServiceLocator.cs 2008-02-09 16:10:55 UTC (rev 63) +++ trunk/Source/StructureMap.AutoMocking/RhinoMocksServiceLocator.cs 2008-02-12 15:23:15 UTC (rev 64) @@ -21,12 +21,12 @@ public T Service<T>() { - return _mocks.CreateMock<T>(); + return _mocks.DynamicMock<T>(); } public object Service(Type serviceType) { - return _mocks.CreateMock(serviceType); + return _mocks.DynamicMock(serviceType); } #endregion Modified: trunk/Source/StructureMap.Testing/AutoMocking/RhinoAutoMockerTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/AutoMocking/RhinoAutoMockerTester.cs 2008-02-09 16:10:55 UTC (rev 63) +++ trunk/Source/StructureMap.Testing/AutoMocking/RhinoAutoMockerTester.cs 2008-02-12 15:23:15 UTC (rev 64) @@ -26,6 +26,30 @@ private AutoMockedInstanceManager _instanceManager; + public class ConcreteThing + { + private readonly IMockedService _service; + private readonly IMockedService2 _service2; + + + public ConcreteThing(IMockedService service, IMockedService2 service2) + { + _service = service; + _service2 = service2; + } + + + public IMockedService Service + { + get { return _service; } + } + + public IMockedService2 Service2 + { + get { return _service2; } + } + } + public class ConcreteClass { private readonly IMockedService _service; @@ -106,6 +130,19 @@ } [Test] + public void UseConcreteClassFor() + { + RhinoAutoMocker<ConcreteClass> mocker = new RhinoAutoMocker<ConcreteClass>(); + mocker.UseConcreteClassFor<ConcreteThing>(); + + ConcreteThing thing = mocker.Get<ConcreteThing>(); + Assert.IsInstanceOfType(typeof(ConcreteThing), thing); + + Assert.AreSame(mocker.Get<IMockedService>(), thing.Service); + Assert.AreSame(mocker.Get<IMockedService2>(), thing.Service2); + } + + [Test] public void AutoFillAConcreteClassWithMocks() { IMockedService service = _instanceManager.CreateInstance<IMockedService>(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <us...@us...> - 2008-02-14 04:10:09
|
Revision: 65 http://structuremap.svn.sourceforge.net/structuremap/?rev=65&view=rev Author: ussherm Date: 2008-02-13 20:10:06 -0800 (Wed, 13 Feb 2008) Log Message: ----------- - Generating strongly-named assemblies (StructureMap and StructureMap.AutoMocking) - Also adding a few SVN ignore attributes. :) Modified Paths: -------------- trunk/Source/StructureMap/StructureMap.csproj trunk/Source/StructureMap.AutoMocking/StructureMap.AutoMocking.csproj trunk/Source/StructureMap.sln Added Paths: ----------- trunk/Source/StructureMap/Properties/ trunk/Source/StructureMap/Properties/AssemblyInfo.cs trunk/Source/structuremap.snk Removed Paths: ------------- trunk/Source/StructureMap/AssemblyInfo.cs Property Changed: ---------------- trunk/Source/StructureMap.AutoMocking/ trunk/Source/StructureMap.DataAccess/ trunk/Source/StructureMap.Testing.GenericWidgets/ Deleted: trunk/Source/StructureMap/AssemblyInfo.cs =================================================================== --- trunk/Source/StructureMap/AssemblyInfo.cs 2008-02-12 15:23:15 UTC (rev 64) +++ trunk/Source/StructureMap/AssemblyInfo.cs 2008-02-14 04:10:06 UTC (rev 65) @@ -1,12 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -// - -[assembly : AssemblyTitle("StructureMap")] -[assembly : AssemblyDescription("Main Library")] -[assembly : InternalsVisibleTo("StructureMap.AutoMocking")] \ No newline at end of file Copied: trunk/Source/StructureMap/Properties/AssemblyInfo.cs (from rev 64, trunk/Source/StructureMap/AssemblyInfo.cs) =================================================================== --- trunk/Source/StructureMap/Properties/AssemblyInfo.cs (rev 0) +++ trunk/Source/StructureMap/Properties/AssemblyInfo.cs 2008-02-14 04:10:06 UTC (rev 65) @@ -0,0 +1,12 @@ +using System.Reflection; +using System.Runtime.CompilerServices; + +// +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +// + +[assembly: AssemblyTitle("StructureMap")] +[assembly: AssemblyDescription("Main Library")] +[assembly: InternalsVisibleTo("StructureMap.AutoMocking, PublicKey=00240000048000009400000006020000002400005253413100040000010001008d9a2a76e43cd9b1b1944b1f3b489a046b33f0bcd755b25cc5d3ed7b18ded38240d6db7578cd986c72d3feb4f94a7ab26fcfa41e3e4f41cf2c029fba91159db05c44d63f0b2bfac24353a07f4a1230dd3d4240340adafa2275277fa083c75958062cd0e60016701db6af7ae718efdf1e802a840595b49c290964255b3c60c494")] \ No newline at end of file Modified: trunk/Source/StructureMap/StructureMap.csproj =================================================================== --- trunk/Source/StructureMap/StructureMap.csproj 2008-02-12 15:23:15 UTC (rev 64) +++ trunk/Source/StructureMap/StructureMap.csproj 2008-02-14 04:10:06 UTC (rev 65) @@ -11,8 +11,7 @@ <AssemblyKeyContainerName> </AssemblyKeyContainerName> <AssemblyName>StructureMap</AssemblyName> - <AssemblyOriginatorKeyFile> - </AssemblyOriginatorKeyFile> + <AssemblyOriginatorKeyFile>..\structuremap.snk</AssemblyOriginatorKeyFile> <DefaultClientScript>JScript</DefaultClientScript> <DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout> <DefaultTargetSchema>IE50</DefaultTargetSchema> @@ -26,6 +25,7 @@ </FileUpgradeFlags> <UpgradeBackupLocation> </UpgradeBackupLocation> + <SignAssembly>true</SignAssembly> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <OutputPath>bin\Debug\</OutputPath> @@ -115,7 +115,7 @@ <Link>CommonAssemblyInfo.cs</Link> <SubType>Code</SubType> </Compile> - <Compile Include="AssemblyInfo.cs"> + <Compile Include="Properties\AssemblyInfo.cs"> <SubType>Code</SubType> </Compile> <Compile Include="Attributes\DefaultConstructorAttribute.cs"> @@ -575,6 +575,11 @@ <SubType>Designer</SubType> </EmbeddedResource> </ItemGroup> + <ItemGroup> + <None Include="..\structuremap.snk"> + <Link>Properties\structuremap.snk</Link> + </None> + </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <PropertyGroup> <PreBuildEvent> Property changes on: trunk/Source/StructureMap.AutoMocking ___________________________________________________________________ Name: svn:ignore + bin obj Modified: trunk/Source/StructureMap.AutoMocking/StructureMap.AutoMocking.csproj =================================================================== --- trunk/Source/StructureMap.AutoMocking/StructureMap.AutoMocking.csproj 2008-02-12 15:23:15 UTC (rev 64) +++ trunk/Source/StructureMap.AutoMocking/StructureMap.AutoMocking.csproj 2008-02-14 04:10:06 UTC (rev 65) @@ -9,6 +9,8 @@ <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>StructureMap.AutoMocking</RootNamespace> <AssemblyName>StructureMap.AutoMocking</AssemblyName> + <SignAssembly>true</SignAssembly> + <AssemblyOriginatorKeyFile>..\structuremap.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> @@ -53,6 +55,11 @@ <Name>StructureMap</Name> </ProjectReference> </ItemGroup> + <ItemGroup> + <None Include="..\structuremap.snk"> + <Link>Properties\structuremap.snk</Link> + </None> + </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. Property changes on: trunk/Source/StructureMap.DataAccess ___________________________________________________________________ Name: svn:ignore - bin obj + bin obj StructureMap.DataAccess.ndoc.xml Property changes on: trunk/Source/StructureMap.Testing.GenericWidgets ___________________________________________________________________ Name: svn:ignore - obj + obj bin Modified: trunk/Source/StructureMap.sln =================================================================== --- trunk/Source/StructureMap.sln 2008-02-12 15:23:15 UTC (rev 64) +++ trunk/Source/StructureMap.sln 2008-02-14 04:10:06 UTC (rev 65) @@ -1,30 +1,82 @@ Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap", "StructureMap\StructureMap.csproj", "{3F36EA80-2F9A-4DAD-BA27-5AC6163A2EE3}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.Diagnostics", "StructureMap.Diagnostics\StructureMap.Diagnostics.csproj", "{52CDE969-625F-4FB6-8EC5-CD297FD809CA}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.Testing", "StructureMap.Testing\StructureMap.Testing.csproj", "{63C2742D-B6E2-484F-AFDB-346873075C5E}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.Testing.Widget", "StructureMap.Testing.Widget\StructureMap.Testing.Widget.csproj", "{E21E1651-3E32-47B7-A290-F461E63FEAD2}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.Testing.Widget2", "StructureMap.Testing.Widget2\StructureMap.Testing.Widget2.csproj", "{027E996C-75E8-40F8-9073-0E3B77A6BE1F}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.Testing.Widget3", "StructureMap.Testing.Widget3\StructureMap.Testing.Widget3.csproj", "{C8878328-281F-4F4F-8D6E-88C60F304B89}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.Testing.Widget4", "StructureMap.Testing.Widget4\StructureMap.Testing.Widget4.csproj", "{901D15CB-EF37-4F84-864B-E70F4B5F1DFF}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.Testing.Widget5", "StructureMap.Testing.Widget5\StructureMap.Testing.Widget5.csproj", "{CAB97F7F-FB75-410C-898A-88DCAAC036BE}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.DeploymentTasks", "StructureMap.DeploymentTasks\StructureMap.DeploymentTasks.csproj", "{DB6A0B91-873E-4E04-866A-7483E136A8D4}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.Testing.DeploymentTasks", "StructureMap.Testing.DeploymentTasks\StructureMap.Testing.DeploymentTasks.csproj", "{195EB3B0-96D2-4047-B091-E858690C741C}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.Client", "StructureMap.Client\StructureMap.Client.csproj", "{887C4441-07A4-489D-B8D9-EFE9D28A47CA}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMapExplorer", "StructureMapExplorer\StructureMapExplorer.csproj", "{51039D04-6DB6-44BD-B827-39C86482D9F0}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{93877CE0-BA48-4F28-B372-B8E802CEE085}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection ProjectSection(SolutionItems) = preProject ..\Docs\Basic Architecture.htm = ..\Docs\Basic Architecture.htm CommonAssemblyInfo.cs = CommonAssemblyInfo.cs @@ -38,6 +90,7 @@ ..\Docs\SingletonInjection.htm = ..\Docs\SingletonInjection.htm ..\Docs\structuremap.deployment.htm = ..\Docs\structuremap.deployment.htm StructureMap.ndoc = StructureMap.ndoc + structuremap.snk = structuremap.snk ..\Docs\structuremap.verification.htm = ..\Docs\structuremap.verification.htm ..\Docs\StructureMap.vsd = ..\Docs\StructureMap.vsd ..\Docs\StructureMapDoctor.htm = ..\Docs\StructureMapDoctor.htm @@ -47,14 +100,34 @@ EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.Testing.GenericWidgets", "StructureMap.Testing.GenericWidgets\StructureMap.Testing.GenericWidgets.csproj", "{C205EA4C-4CD0-4221-A3CB-AFD835F0B263}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.DataAccess", "StructureMap.DataAccess\StructureMap.DataAccess.csproj", "{DB798C07-0C82-4298-8BAA-D702CF96C28E}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Widgets", "Widgets", "{E1C10209-160D-4054-ACB7-478A9FDCF84C}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GUI", "GUI", "{4F638ECF-2A69-4D6A-9B68-05CC40951217}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.AutoMocking", "StructureMap.AutoMocking\StructureMap.AutoMocking.csproj", "{0ED1B206-A1C9-4A52-BA87-3BA416C8725C}" + ProjectSection(WebsiteProperties) = preProject + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.Debug = "False" + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Added: trunk/Source/structuremap.snk =================================================================== (Binary files differ) Property changes on: trunk/Source/structuremap.snk ___________________________________________________________________ Name: svn:mime-type + application/octet-stream This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jer...@us...> - 2008-04-06 18:45:52
|
Revision: 71 http://structuremap.svn.sourceforge.net/structuremap/?rev=71&view=rev Author: jeremydmiller Date: 2008-04-06 11:45:47 -0700 (Sun, 06 Apr 2008) Log Message: ----------- start of the new Pipeline Modified Paths: -------------- trunk/Source/StructureMap/StructureMap.csproj trunk/Source/StructureMap.Testing/StructureMap.Testing.csproj trunk/Source/StructureMap.Testing.Widget/ArrayConstruction.cs trunk/Source/StructureMap.Testing.Widget/Decision.cs trunk/Source/StructureMap.Testing.Widget/Hierarchy.cs trunk/Source/StructureMap.Testing.Widget2/EnumerationCheck.cs trunk/Source/StructureMap.Testing.Widget5/BasicGridColumnInstanceBuilder.cs Added Paths: ----------- trunk/Source/StructureMap/Pipeline/ trunk/Source/StructureMap/Pipeline/ConfiguredInstance.cs trunk/Source/StructureMap/Pipeline/DefaultInstance.cs trunk/Source/StructureMap/Pipeline/Instance.cs trunk/Source/StructureMap/Pipeline/LiteralInstance.cs trunk/Source/StructureMap/Pipeline/PrototypeInstance.cs trunk/Source/StructureMap/Pipeline/ReferencedInstance.cs trunk/Source/StructureMap/Pipeline/UserControlInstance.cs trunk/Source/StructureMap.Testing/Pipeline/ trunk/Source/StructureMap.Testing/Pipeline/DefaultInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/InstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/LiteralInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/PrototypeInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/ReferencedInstanceTester.cs Property Changed: ---------------- trunk/Source/ Property changes on: trunk/Source ___________________________________________________________________ Name: svn:ignore - *.suo _ReSharper.StructureMap PrecompiledWeb *.resharper *.user + *.suo _ReSharper.StructureMap PrecompiledWeb *.resharper *.user Ankh.Load _UpgradeReport_Files UpgradeLog.XML UpgradeLog2.XML UpgradeLog3.XML UpgradeLog4.XML Added: trunk/Source/StructureMap/Pipeline/ConfiguredInstance.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/ConfiguredInstance.cs (rev 0) +++ trunk/Source/StructureMap/Pipeline/ConfiguredInstance.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace StructureMap.Pipeline +{ + public interface IConfiguredInstance + { + + } + + public class ConfiguredInstance : Instance + { + + + protected override T build<T>(IInstanceCreator creator) + { + throw new NotImplementedException(); + } + + public override void Diagnose<T>(IInstanceCreator creator, IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + + public override void Describe<T>(IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + } +} Added: trunk/Source/StructureMap/Pipeline/DefaultInstance.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/DefaultInstance.cs (rev 0) +++ trunk/Source/StructureMap/Pipeline/DefaultInstance.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace StructureMap.Pipeline +{ + public class DefaultInstance : Instance + { + protected override T build<T>(IInstanceCreator creator) + { + return creator.CreateInstance<T>(); + } + + public override void Diagnose<T>(IInstanceCreator creator, IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + + public override void Describe<T>(IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + } +} Added: trunk/Source/StructureMap/Pipeline/Instance.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/Instance.cs (rev 0) +++ trunk/Source/StructureMap/Pipeline/Instance.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,45 @@ +using System; +using System.Web.UI; +using StructureMap.Interceptors; + +namespace StructureMap.Pipeline +{ + public interface IInstanceCreator + { + T CreateInstance<T>(string referenceKey); + T CreateInstance<T>(); + } + + public interface IInstanceDiagnostics + { + } + + public abstract class Instance + { + private string _name; + private InstanceInterceptor _interceptor = new NulloInterceptor(); + + public string Name + { + get { return _name; } + set { _name = value; } + } + + public InstanceInterceptor Interceptor + { + get { return _interceptor; } + set { _interceptor = value; } + } + + public T Build<T>(IInstanceCreator creator) where T : class + { + T rawValue = build<T>(creator); + return (T) _interceptor.Process(rawValue); + } + + protected abstract T build<T>(IInstanceCreator creator) where T : class; + + public abstract void Diagnose<T>(IInstanceCreator creator, IInstanceDiagnostics diagnostics) where T : class; + public abstract void Describe<T>(IInstanceDiagnostics diagnostics) where T : class; + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Pipeline/LiteralInstance.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/LiteralInstance.cs (rev 0) +++ trunk/Source/StructureMap/Pipeline/LiteralInstance.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,34 @@ +using System; + +namespace StructureMap.Pipeline +{ + public class LiteralInstance<PLUGINTYPE> : Instance + { + private PLUGINTYPE _object; + + public LiteralInstance(PLUGINTYPE anObject) + { + _object = anObject; + + // TODO: VALIDATE NOT NULL + } + + protected override T build<T>(IInstanceCreator creator) + { + T returnValue = _object as T; + // TODO: VALIDATE THE CAST AND NULL + + return returnValue; + } + + public override void Diagnose<T>(IInstanceCreator creator, IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + + public override void Describe<T>(IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Pipeline/PrototypeInstance.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/PrototypeInstance.cs (rev 0) +++ trunk/Source/StructureMap/Pipeline/PrototypeInstance.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,32 @@ +using System; + +namespace StructureMap.Pipeline +{ + public class PrototypeInstance : Instance + { + private ICloneable _prototype; + + + public PrototypeInstance(ICloneable prototype) + { + _prototype = prototype; + } + + + protected override T build<T>(IInstanceCreator creator) + { + // TODO: VALIDATION IF IT CAN'T BE CAST + return (T) _prototype.Clone(); + } + + public override void Diagnose<T>(IInstanceCreator creator, IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + + public override void Describe<T>(IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Pipeline/ReferencedInstance.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/ReferencedInstance.cs (rev 0) +++ trunk/Source/StructureMap/Pipeline/ReferencedInstance.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,31 @@ +using System; + +namespace StructureMap.Pipeline +{ + public class ReferencedInstance : Instance + { + private readonly string _referenceKey; + + + public ReferencedInstance(string referenceKey) + { + // TODO: VALIDATION if referenceKey is null or empty + _referenceKey = referenceKey; + } + + protected override T build<T>(IInstanceCreator creator) + { + return creator.CreateInstance<T>(_referenceKey); + } + + public override void Diagnose<T>(IInstanceCreator creator, IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + + public override void Describe<T>(IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Pipeline/UserControlInstance.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/UserControlInstance.cs (rev 0) +++ trunk/Source/StructureMap/Pipeline/UserControlInstance.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,31 @@ +using System; +using System.Web.UI; + +namespace StructureMap.Pipeline +{ + public class UserControlInstance : Instance + { + private readonly string _url; + + public UserControlInstance(string url) + { + _url = url; + } + + protected override T build<T>(IInstanceCreator creator) + { + // TODO: VALIDATION if it doesn't cast or can't be built + return new Page().LoadControl(_url) as T; + } + + public override void Diagnose<T>(IInstanceCreator creator, IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + + public override void Describe<T>(IInstanceDiagnostics diagnostics) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file Modified: trunk/Source/StructureMap/StructureMap.csproj =================================================================== --- trunk/Source/StructureMap/StructureMap.csproj 2008-04-06 16:26:03 UTC (rev 70) +++ trunk/Source/StructureMap/StructureMap.csproj 2008-04-06 18:45:47 UTC (rev 71) @@ -115,6 +115,13 @@ <Link>CommonAssemblyInfo.cs</Link> <SubType>Code</SubType> </Compile> + <Compile Include="Pipeline\ConfiguredInstance.cs" /> + <Compile Include="Pipeline\DefaultInstance.cs" /> + <Compile Include="Pipeline\Instance.cs" /> + <Compile Include="Pipeline\LiteralInstance.cs" /> + <Compile Include="Pipeline\PrototypeInstance.cs" /> + <Compile Include="Pipeline\ReferencedInstance.cs" /> + <Compile Include="Pipeline\UserControlInstance.cs" /> <Compile Include="Properties\AssemblyInfo.cs"> <SubType>Code</SubType> </Compile> Added: trunk/Source/StructureMap.Testing/Pipeline/DefaultInstanceTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Pipeline/DefaultInstanceTester.cs (rev 0) +++ trunk/Source/StructureMap.Testing/Pipeline/DefaultInstanceTester.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,44 @@ +using NUnit.Framework; +using Rhino.Mocks; +using StructureMap.Pipeline; + +namespace StructureMap.Testing.Pipeline +{ + [TestFixture] + public class DefaultInstanceTester + { + #region Setup/Teardown + + [SetUp] + public void SetUp() + { + } + + #endregion + + [Test] + public void Build_happy_path() + { + MockRepository mocks = new MockRepository(); + StructureMap.Pipeline.IInstanceCreator instanceCreator = + mocks.CreateMock<StructureMap.Pipeline.IInstanceCreator>(); + + DefaultClass theDefault = new DefaultClass(); + + + using (mocks.Record()) + { + Expect.Call(instanceCreator.CreateInstance<IDefault>()).Return(theDefault); + } + + using (mocks.Playback()) + { + DefaultInstance instance = new DefaultInstance(); + Assert.AreSame(theDefault, instance.Build<IDefault>(instanceCreator)); + } + } + + public interface IDefault {} + public class DefaultClass : IDefault {} + } +} \ No newline at end of file Added: trunk/Source/StructureMap.Testing/Pipeline/InstanceTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Pipeline/InstanceTester.cs (rev 0) +++ trunk/Source/StructureMap.Testing/Pipeline/InstanceTester.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,62 @@ +using NUnit.Framework; +using Rhino.Mocks; +using StructureMap.Interceptors; +using StructureMap.Pipeline; +using StructureMap.Testing.Container.Interceptors; + +namespace StructureMap.Testing.Pipeline +{ + [TestFixture] + public class InstanceTester + { + #region Setup/Teardown + + [SetUp] + public void SetUp() + { + } + + [Test] + public void Instance_Build_Calls_into_its_Interceptor() + { + MockRepository mocks = new MockRepository(); + InstanceInterceptor interceptor = mocks.CreateMock<InstanceInterceptor>(); + + InstanceUnderTest instanceUnderTest = new InstanceUnderTest(); + instanceUnderTest.Interceptor = interceptor; + + object objectReturnedByInterceptor = new object(); + using (mocks.Record()) + { + Expect.Call(interceptor.Process(instanceUnderTest.TheInstanceThatWasBuilt)).Return(objectReturnedByInterceptor); + } + + using (mocks.Playback()) + { + Assert.AreEqual(objectReturnedByInterceptor, instanceUnderTest.Build<object>(null)); + } + } + + #endregion + } + + public class InstanceUnderTest : Instance + { + public object TheInstanceThatWasBuilt = new object(); + + public override void Diagnose<T>(StructureMap.Pipeline.IInstanceCreator creator, IInstanceDiagnostics diagnostics) + { + throw new System.NotImplementedException(); + } + + public override void Describe<T>(IInstanceDiagnostics diagnostics) + { + throw new System.NotImplementedException(); + } + + protected override T build<T>(StructureMap.Pipeline.IInstanceCreator creator) + { + return (T) TheInstanceThatWasBuilt; + } + } +} \ No newline at end of file Added: trunk/Source/StructureMap.Testing/Pipeline/LiteralInstanceTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Pipeline/LiteralInstanceTester.cs (rev 0) +++ trunk/Source/StructureMap.Testing/Pipeline/LiteralInstanceTester.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,36 @@ +using NUnit.Framework; +using Rhino.Mocks; +using StructureMap.Pipeline; + +namespace StructureMap.Testing.Pipeline +{ + [TestFixture] + public class LiteralInstanceTester + { + [SetUp] + public void SetUp() + { + } + + [Test] + public void Build_happy_path() + { + ATarget target = new ATarget(); + LiteralInstance<ITarget> instance = new LiteralInstance<ITarget>(target); + Assert.AreSame(target, instance.Build<ITarget>(null)); + } + + public interface ITarget + { + + } + + public class ATarget : ITarget + { + public override string ToString() + { + return "the description of ATarget"; + } + } + } +} Added: trunk/Source/StructureMap.Testing/Pipeline/PrototypeInstanceTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Pipeline/PrototypeInstanceTester.cs (rev 0) +++ trunk/Source/StructureMap.Testing/Pipeline/PrototypeInstanceTester.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,68 @@ +using System; +using NUnit.Framework; +using Rhino.Mocks; +using StructureMap.Pipeline; + +namespace StructureMap.Testing.Pipeline +{ + [TestFixture] + public class PrototypeInstanceTester + { + [SetUp] + public void SetUp() + { + } + + [Test] + public void Build_a_clone() + { + PrototypeTarget target = new PrototypeTarget("Jeremy"); + PrototypeInstance instance = new PrototypeInstance(target); + + object returnedValue = instance.Build<PrototypeTarget>(null); + + Assert.AreEqual(target, returnedValue); + Assert.AreNotSame(target, returnedValue); + } + + public class PrototypeTarget : ICloneable, IEquatable<PrototypeTarget> + { + private string _name; + + + public PrototypeTarget(string name) + { + _name = name; + } + + public string Name + { + get { return _name; } + set { _name = value; } + } + + + public bool Equals(PrototypeTarget prototypeTarget) + { + if (prototypeTarget == null) return false; + return Equals(_name, prototypeTarget._name); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(this, obj)) return true; + return Equals(obj as PrototypeTarget); + } + + public override int GetHashCode() + { + return _name != null ? _name.GetHashCode() : 0; + } + + public object Clone() + { + return this.MemberwiseClone(); + } + } + } +} Added: trunk/Source/StructureMap.Testing/Pipeline/ReferencedInstanceTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Pipeline/ReferencedInstanceTester.cs (rev 0) +++ trunk/Source/StructureMap.Testing/Pipeline/ReferencedInstanceTester.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -0,0 +1,43 @@ +using NUnit.Framework; +using Rhino.Mocks; +using StructureMap.Pipeline; + +namespace StructureMap.Testing.Pipeline +{ + [TestFixture] + public class ReferencedInstanceTester + { + [SetUp] + public void SetUp() + { + } + + [Test] + public void Create_referenced_instance_happy_path() + { + MockRepository mocks = new MockRepository(); + StructureMap.Pipeline.IInstanceCreator instanceCreator = mocks.CreateMock<StructureMap.Pipeline.IInstanceCreator>(); + + ConcreteReferenced returnedValue = new ConcreteReferenced(); + string theReferenceKey = "theReferenceKey"; + ReferencedInstance instance = new ReferencedInstance(theReferenceKey); + + using (mocks.Record()) + { + Expect.Call(instanceCreator.CreateInstance<IReferenced>(theReferenceKey)).Return(returnedValue); + } + + using (mocks.Playback()) + { + Assert.AreSame(returnedValue, instance.Build<IReferenced>(instanceCreator)); + } + } + + public interface IReferenced + { + + } + + public class ConcreteReferenced : IReferenced{} + } +} Modified: trunk/Source/StructureMap.Testing/StructureMap.Testing.csproj =================================================================== --- trunk/Source/StructureMap.Testing/StructureMap.Testing.csproj 2008-04-06 16:26:03 UTC (rev 70) +++ trunk/Source/StructureMap.Testing/StructureMap.Testing.csproj 2008-04-06 18:45:47 UTC (rev 71) @@ -365,6 +365,11 @@ <Compile Include="ObjectMother.cs"> <SubType>Code</SubType> </Compile> + <Compile Include="Pipeline\DefaultInstanceTester.cs" /> + <Compile Include="Pipeline\InstanceTester.cs" /> + <Compile Include="Pipeline\LiteralInstanceTester.cs" /> + <Compile Include="Pipeline\PrototypeInstanceTester.cs" /> + <Compile Include="Pipeline\ReferencedInstanceTester.cs" /> <Compile Include="StructureMapConfigCreator.cs" /> <Compile Include="StructureMapConfigurationTester.cs" /> <Compile Include="TestData\DataMother.cs"> Modified: trunk/Source/StructureMap.Testing.Widget/ArrayConstruction.cs =================================================================== --- trunk/Source/StructureMap.Testing.Widget/ArrayConstruction.cs 2008-04-06 16:26:03 UTC (rev 70) +++ trunk/Source/StructureMap.Testing.Widget/ArrayConstruction.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -1,3 +1,5 @@ +using StructureMap.Pipeline; + namespace StructureMap.Testing.Widget { public interface IList Modified: trunk/Source/StructureMap.Testing.Widget/Decision.cs =================================================================== --- trunk/Source/StructureMap.Testing.Widget/Decision.cs 2008-04-06 16:26:03 UTC (rev 70) +++ trunk/Source/StructureMap.Testing.Widget/Decision.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -1,3 +1,5 @@ +using StructureMap.Pipeline; + namespace StructureMap.Testing.Widget { public class Decision Modified: trunk/Source/StructureMap.Testing.Widget/Hierarchy.cs =================================================================== --- trunk/Source/StructureMap.Testing.Widget/Hierarchy.cs 2008-04-06 16:26:03 UTC (rev 70) +++ trunk/Source/StructureMap.Testing.Widget/Hierarchy.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -1,3 +1,5 @@ +using StructureMap.Pipeline; + namespace StructureMap.Testing.Widget { [PluginFamily, Pluggable("Default", "")] @@ -106,11 +108,11 @@ } - public override object BuildInstance(InstanceMemento memento) + public override object BuildInstance(InstanceMemento instance) { return new Child( - memento.GetProperty("Name"), - (GrandChild) memento.GetChild("MyGrandChild", "StructureMap.Testing.Widget.GrandChild", Manager)); + instance.GetProperty("Name"), + (GrandChild) instance.GetChild("MyGrandChild", "StructureMap.Testing.Widget.GrandChild", Manager)); } } } \ No newline at end of file Modified: trunk/Source/StructureMap.Testing.Widget2/EnumerationCheck.cs =================================================================== --- trunk/Source/StructureMap.Testing.Widget2/EnumerationCheck.cs 2008-04-06 16:26:03 UTC (rev 70) +++ trunk/Source/StructureMap.Testing.Widget2/EnumerationCheck.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -1,4 +1,5 @@ using System; +using StructureMap.Pipeline; namespace StructureMap.Testing.Widget2 { @@ -44,12 +45,12 @@ } - public override object BuildInstance(InstanceMemento memento) + public override object BuildInstance(InstanceMemento instance) { return new Cow( - long.Parse(memento.GetProperty("Weight")), - (BreedEnum) Enum.Parse(typeof (BreedEnum), memento.GetProperty("Breed"), true), - memento.GetProperty("Name")); + long.Parse(instance.GetProperty("Weight")), + (BreedEnum) Enum.Parse(typeof (BreedEnum), instance.GetProperty("Breed"), true), + instance.GetProperty("Name")); } } } \ No newline at end of file Modified: trunk/Source/StructureMap.Testing.Widget5/BasicGridColumnInstanceBuilder.cs =================================================================== --- trunk/Source/StructureMap.Testing.Widget5/BasicGridColumnInstanceBuilder.cs 2008-04-06 16:26:03 UTC (rev 70) +++ trunk/Source/StructureMap.Testing.Widget5/BasicGridColumnInstanceBuilder.cs 2008-04-06 18:45:47 UTC (rev 71) @@ -1,4 +1,5 @@ using System; +using StructureMap.Pipeline; using StructureMap.Testing.Widget; namespace StructureMap.Testing.Widget5 @@ -28,9 +29,9 @@ get { throw new NotImplementedException(); } } - public override object BuildInstance(InstanceMemento memento) + public override object BuildInstance(InstanceMemento instance) { - BasicGridColumn column = new BasicGridColumn(memento.GetProperty("headerText")); + BasicGridColumn column = new BasicGridColumn(instance.GetProperty("headerText")); // column.Widget = // (IWidget) Memento.GetChild("Widget", "StructureMap.Testing.Widget.IWidget", this.Manager); @@ -42,7 +43,7 @@ column.Rules = (Rule[]) - Manager.CreateInstanceArray("StructureMap.Testing.Widget.Rule", memento.GetChildrenArray("Rules")); + Manager.CreateInstanceArray("StructureMap.Testing.Widget.Rule", instance.GetChildrenArray("Rules")); // // column.WrapLines = bool.Parse(Memento.GetProperty("WrapLines")); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jer...@us...> - 2008-05-15 18:15:52
|
Revision: 97 http://structuremap.svn.sourceforge.net/structuremap/?rev=97&view=rev Author: jeremydmiller Date: 2008-05-15 11:15:44 -0700 (Thu, 15 May 2008) Log Message: ----------- Reformatting Modified Paths: -------------- trunk/Source/CommonAssemblyInfo.cs trunk/Source/StructureMap/Attributes/PluginFamilyAttribute.cs trunk/Source/StructureMap/BuildSession.cs trunk/Source/StructureMap/Configuration/ConfigurationParser.cs trunk/Source/StructureMap/Configuration/ConfigurationParserCollection.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs trunk/Source/StructureMap/Configuration/DSL/Registry.cs trunk/Source/StructureMap/Configuration/FamilyParser.cs trunk/Source/StructureMap/Configuration/IGraphBuilder.cs trunk/Source/StructureMap/Configuration/ProfileAndMachineParser.cs trunk/Source/StructureMap/Configuration/ProfileBuilder.cs trunk/Source/StructureMap/Configuration/XmlConstants.cs trunk/Source/StructureMap/Diagnostics/Tokens.cs trunk/Source/StructureMap/Emitting/BuildInstanceMethod.cs trunk/Source/StructureMap/Emitting/ClassBuilder.cs trunk/Source/StructureMap/Emitting/InstanceBuilderAssembly.cs trunk/Source/StructureMap/Emitting/Parameters/ChildArrayParameterEmitter.cs trunk/Source/StructureMap/Emitting/Parameters/ParameterEmitter.cs trunk/Source/StructureMap/Emitting/Parameters/StringParameterEmitter.cs trunk/Source/StructureMap/Graph/AssemblyScanner.cs trunk/Source/StructureMap/Graph/Constructor.cs trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs trunk/Source/StructureMap/Graph/IPluginFamily.cs trunk/Source/StructureMap/Graph/Plugin.cs trunk/Source/StructureMap/Graph/PluginCollection.cs trunk/Source/StructureMap/Graph/PluginFamily.cs trunk/Source/StructureMap/Graph/PluginFamilyCollection.cs trunk/Source/StructureMap/Graph/SetterPropertyCollection.cs trunk/Source/StructureMap/Graph/TypePath.cs trunk/Source/StructureMap/Graph/TypeRules.cs trunk/Source/StructureMap/IInstanceFactory.cs trunk/Source/StructureMap/IInstanceManager.cs trunk/Source/StructureMap/InstanceBuilderList.cs trunk/Source/StructureMap/InstanceFactory.cs trunk/Source/StructureMap/InstanceFamily.cs trunk/Source/StructureMap/InstanceManager.cs trunk/Source/StructureMap/InstanceMemento.cs trunk/Source/StructureMap/Interceptors/FilteredInstanceInterceptor.cs trunk/Source/StructureMap/Interceptors/InterceptorLibrary.cs trunk/Source/StructureMap/Interceptors/Interceptors.cs trunk/Source/StructureMap/MemoryInstanceMemento.cs trunk/Source/StructureMap/ObjectFactory.cs trunk/Source/StructureMap/Pipeline/BuildPolicy.cs trunk/Source/StructureMap/Pipeline/CacheInterceptor.cs trunk/Source/StructureMap/Pipeline/ConfiguredInstance.cs trunk/Source/StructureMap/Pipeline/DefaultInstance.cs trunk/Source/StructureMap/Pipeline/ExplicitArguments.cs trunk/Source/StructureMap/Pipeline/HybridBuildPolicy.cs trunk/Source/StructureMap/Pipeline/IConfiguredInstance.cs trunk/Source/StructureMap/Pipeline/ILocationPolicy.cs trunk/Source/StructureMap/Pipeline/InstanceMementoPropertyReader.cs trunk/Source/StructureMap/Pipeline/LiteralInstance.cs trunk/Source/StructureMap/Pipeline/Profile.cs trunk/Source/StructureMap/Pipeline/ProfileManager.cs trunk/Source/StructureMap/Pipeline/ReferencedInstance.cs trunk/Source/StructureMap/Pipeline/ThreadLocalStoragePolicy.cs trunk/Source/StructureMap/Pipeline/UserControlInstance.cs trunk/Source/StructureMap/PipelineGraph.cs trunk/Source/StructureMap/PluginGraphBuilder.cs trunk/Source/StructureMap/Properties/AssemblyInfo.cs trunk/Source/StructureMap/Source/XmlAttributeInstanceMemento.cs trunk/Source/StructureMap/Source/XmlNodeInstanceMemento.cs Modified: trunk/Source/CommonAssemblyInfo.cs =================================================================== --- trunk/Source/CommonAssemblyInfo.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/CommonAssemblyInfo.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,4 +1,3 @@ -using System; using System.Reflection; using System.Runtime.InteropServices; @@ -12,11 +11,10 @@ // </auto-generated> //------------------------------------------------------------------------------ -[assembly: ComVisibleAttribute(false)] -[assembly: AssemblyVersionAttribute("2.5.0.0000")] -[assembly: AssemblyCopyrightAttribute("Copyright (c) 2007, Jeremy D. Miller")] -[assembly: AssemblyProductAttribute("StructureMap")] -[assembly: AssemblyCompanyAttribute("")] -[assembly: AssemblyConfigurationAttribute("release")] -[assembly: AssemblyInformationalVersionAttribute("2.5.0.0000")] - +[assembly : ComVisible(false)] +[assembly : AssemblyVersion("2.5.0.0000")] +[assembly : AssemblyCopyrightAttribute("Copyright (c) 2007, Jeremy D. Miller")] +[assembly : AssemblyProductAttribute("StructureMap")] +[assembly : AssemblyCompanyAttribute("")] +[assembly : AssemblyConfigurationAttribute("release")] +[assembly : AssemblyInformationalVersionAttribute("2.5.0.0000")] \ No newline at end of file Modified: trunk/Source/StructureMap/Attributes/PluginFamilyAttribute.cs =================================================================== --- trunk/Source/StructureMap/Attributes/PluginFamilyAttribute.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Attributes/PluginFamilyAttribute.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -94,7 +94,8 @@ } catch (Exception ex) { - throw new StructureMapException(122, ex, SourceType.FullName, family.PluginType.AssemblyQualifiedName); + throw new StructureMapException(122, ex, SourceType.FullName, + family.PluginType.AssemblyQualifiedName); } } Modified: trunk/Source/StructureMap/BuildSession.cs =================================================================== --- trunk/Source/StructureMap/BuildSession.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/BuildSession.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using StructureMap.Interceptors; using StructureMap.Pipeline; @@ -8,8 +6,8 @@ { public class BuildSession : IBuildSession { + private readonly InterceptorLibrary _interceptorLibrary; private readonly PipelineGraph _pipelineGraph; - private readonly InterceptorLibrary _interceptorLibrary; public BuildSession(PipelineGraph pipelineGraph, InterceptorLibrary interceptorLibrary) { @@ -17,10 +15,7 @@ _interceptorLibrary = interceptorLibrary; } - private IInstanceFactory forType(Type pluginType) - { - return _pipelineGraph.ForType(pluginType); - } + #region IBuildSession Members public object CreateInstance(Type type, string name) { @@ -79,5 +74,12 @@ { return forType(pluginType).FindBuilderByConcreteKey(concreteKey); } + + #endregion + + private IInstanceFactory forType(Type pluginType) + { + return _pipelineGraph.ForType(pluginType); + } } -} +} \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/ConfigurationParser.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ConfigurationParser.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/ConfigurationParser.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; @@ -48,7 +47,7 @@ includedPath = Path.Combine(folder, fileName); includedDoc.Load(includedPath); - + ConfigurationParser parser = new ConfigurationParser(includedDoc.DocumentElement); list.Add(parser); } @@ -86,7 +85,7 @@ public ConfigurationParser(XmlNode structureMapNode) { _structureMapNode = structureMapNode; - + // TODO: 3.5 cleanup with extension method XmlMementoStyle mementoStyle = XmlMementoStyle.NodeNormalized; @@ -128,13 +127,9 @@ foreach (XmlElement familyElement in familyNodes) { TypePath typePath = TypePath.CreateFromXmlNode(familyElement); - - builder.ConfigureFamily(typePath, delegate(PluginFamily family) - { - attachInstances(family, familyElement, builder); - }); - + builder.ConfigureFamily(typePath, + delegate(PluginFamily family) { attachInstances(family, familyElement, builder); }); } } Modified: trunk/Source/StructureMap/Configuration/ConfigurationParserCollection.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ConfigurationParserCollection.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/ConfigurationParserCollection.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -11,8 +11,8 @@ public class ConfigurationParserCollection { private readonly List<FetchNodeDelegate> _fetchers = new List<FetchNodeDelegate>(); + private readonly List<string> _otherFiles = new List<string>(); private bool _ignoreDefaultFile = false; - private readonly List<string> _otherFiles = new List<string>(); private bool _useAndEnforceExistenceOfDefaultFile = false; public bool UseAndEnforceExistenceOfDefaultFile @@ -55,7 +55,8 @@ private bool shouldUseStructureMapConfigFile(string pathToStructureMapConfig) { - return (_useAndEnforceExistenceOfDefaultFile || File.Exists(pathToStructureMapConfig)) && !_ignoreDefaultFile; + return + (_useAndEnforceExistenceOfDefaultFile || File.Exists(pathToStructureMapConfig)) && !_ignoreDefaultFile; } private static void addParsersFromFile(string filename, List<ConfigurationParser> list) Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -4,11 +4,9 @@ using StructureMap.Graph; using StructureMap.Interceptors; using StructureMap.Pipeline; -using StructureMap.Source; namespace StructureMap.Configuration.DSL.Expressions { - /// <summary> /// Represents the parameters for creating instances of a given Type /// </summary> @@ -59,10 +57,7 @@ public CreatePluginFamilyExpression<PLUGINTYPE> AddInstance(Instance instance) { // TODO: Validate pluggability - _alterations.Add(delegate(PluginFamily family) - { - family.AddInstance(instance); - }); + _alterations.Add(delegate(PluginFamily family) { family.AddInstance(instance); }); return this; } @@ -96,10 +91,7 @@ /// <returns></returns> public CreatePluginFamilyExpression<PLUGINTYPE> CacheBy(InstanceScope scope) { - _alterations.Add(delegate(PluginFamily family) - { - family.SetScopeTo(scope); - }); + _alterations.Add(delegate(PluginFamily family) { family.SetScopeTo(scope); }); return this; } @@ -127,7 +119,7 @@ return target; }; - PluginTypeInterceptor interceptor = new PluginTypeInterceptor(typeof(PLUGINTYPE), function); + PluginTypeInterceptor interceptor = new PluginTypeInterceptor(typeof (PLUGINTYPE), function); graph.InterceptorLibrary.AddInterceptor(interceptor); }); @@ -138,15 +130,12 @@ { _children.Add( delegate(PluginGraph graph) - { - InterceptionFunction function = delegate(object target) - { - return handler((PLUGINTYPE)target); - }; + { + InterceptionFunction function = delegate(object target) { return handler((PLUGINTYPE) target); }; - PluginTypeInterceptor interceptor = new PluginTypeInterceptor(typeof(PLUGINTYPE), function); - graph.InterceptorLibrary.AddInterceptor(interceptor); - }); + PluginTypeInterceptor interceptor = new PluginTypeInterceptor(typeof (PLUGINTYPE), function); + graph.InterceptorLibrary.AddInterceptor(interceptor); + }); return this; } @@ -172,29 +161,20 @@ public CreatePluginFamilyExpression<PLUGINTYPE> InterceptConstructionWith(IBuildInterceptor interceptor) { - _alterations.Add(delegate(PluginFamily family) - { - family.AddInterceptor(interceptor); - }); + _alterations.Add(delegate(PluginFamily family) { family.AddInterceptor(interceptor); }); return this; } public CreatePluginFamilyExpression<PLUGINTYPE> AddInstancesFrom(MementoSource source) { - _alterations.Add(delegate(PluginFamily family) - { - family.AddMementoSource(source); - }); + _alterations.Add(delegate(PluginFamily family) { family.AddMementoSource(source); }); return this; } public CreatePluginFamilyExpression<PLUGINTYPE> AliasConcreteType<PLUGGEDTYPE>(string concreteKey) { - _alterations.Add(delegate(PluginFamily family) - { - family.AddPlugin(typeof(PLUGGEDTYPE), concreteKey); - }); + _alterations.Add(delegate(PluginFamily family) { family.AddPlugin(typeof (PLUGGEDTYPE), concreteKey); }); return this; } Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -11,8 +11,8 @@ { private readonly ProfileExpression _parent; private readonly Type _pluginType; + private Instance _instance; private string _instanceKey = string.Empty; - private Instance _instance; public InstanceDefaultExpression(Type pluginType, ProfileExpression parent) { @@ -37,7 +37,7 @@ { _instanceKey = Profile.InstanceKeyForProfile(profileName); _instance.Name = _instanceKey; - pluginGraph.FindFamily(_pluginType).AddInstance(_instance); + pluginGraph.FindFamily(_pluginType).AddInstance(_instance); } else if (!string.IsNullOrEmpty(_instanceKey)) { @@ -46,7 +46,7 @@ if (_instance != null) { - pluginGraph.ProfileManager.SetDefault(profileName, _pluginType, _instance); + pluginGraph.ProfileManager.SetDefault(profileName, _pluginType, _instance); } else { Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using StructureMap.Graph; Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -66,7 +66,7 @@ public ScanAssembliesExpression IncludeAssemblyContainingType<T>() { - _assemblies.Add(typeof(T).Assembly); + _assemblies.Add(typeof (T).Assembly); return this; } Modified: trunk/Source/StructureMap/Configuration/DSL/Registry.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -112,10 +112,8 @@ { ConfiguredInstance instance = new ConfiguredInstance(); - addExpression(delegate (PluginGraph pluginGraph) - { - pluginGraph.FindFamily(typeof(PLUGINTYPE)).AddInstance(instance); - }); + addExpression( + delegate(PluginGraph pluginGraph) { pluginGraph.FindFamily(typeof (PLUGINTYPE)).AddInstance(instance); }); return instance; } @@ -165,7 +163,7 @@ public LiteralInstance AddInstanceOf<PLUGINTYPE>(PLUGINTYPE target) { LiteralInstance literal = new LiteralInstance(target); - _graph.FindFamily(typeof(PLUGINTYPE)).AddInstance(literal); + _graph.FindFamily(typeof (PLUGINTYPE)).AddInstance(literal); return literal; } @@ -179,7 +177,7 @@ public PrototypeInstance AddPrototypeInstanceOf<PLUGINTYPE>(PLUGINTYPE prototype) { PrototypeInstance expression = new PrototypeInstance((ICloneable) prototype); - _graph.FindFamily(typeof(PLUGINTYPE)).AddInstance(expression); + _graph.FindFamily(typeof (PLUGINTYPE)).AddInstance(expression); return expression; } @@ -235,7 +233,7 @@ PluginFamily family = _graph.FindFamily(typeof (PLUGINTYPE)); family.AddInstance(instance); - + return instance; } Modified: trunk/Source/StructureMap/Configuration/FamilyParser.cs =================================================================== --- trunk/Source/StructureMap/Configuration/FamilyParser.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/FamilyParser.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -2,7 +2,6 @@ using System.Xml; using StructureMap.Attributes; using StructureMap.Graph; -using StructureMap.Interceptors; using StructureMap.Pipeline; using StructureMap.Source; @@ -68,10 +67,11 @@ public void ParseInstanceElement(XmlElement element) { TypePath pluginTypePath = new TypePath(element.GetAttribute(XmlConstants.PLUGIN_TYPE)); - + _builder.ConfigureFamily(pluginTypePath, delegate(PluginFamily family) { - InstanceMemento memento = _mementoCreator.CreateMemento(element); + InstanceMemento memento = + _mementoCreator.CreateMemento(element); family.AddInstance(memento); }); } @@ -98,12 +98,8 @@ InstanceMemento sourceMemento = new XmlAttributeInstanceMemento(sourceNode); string context = "MementoSource for " + TypePath.GetAssemblyQualifiedName(family.PluginType); - _builder.WithSystemObject<MementoSource>(sourceMemento, context, delegate (MementoSource source) - { - family.AddMementoSource(source); - }); - - + _builder.WithSystemObject<MementoSource>(sourceMemento, context, + delegate(MementoSource source) { family.AddMementoSource(source); }); } } @@ -122,14 +118,14 @@ Plugin plugin = new Plugin(pluggedType, concreteKey); family.Plugins.Add(plugin); - foreach (XmlElement setterElement in pluginElement.ChildNodes) + foreach ( + XmlElement setterElement in pluginElement.ChildNodes) { - string setterName = setterElement.GetAttribute("Name"); + string setterName = + setterElement.GetAttribute("Name"); plugin.Setters.Add(setterName); } }); - - } } @@ -142,17 +138,15 @@ return; } - string context = "Creating an InstanceInterceptor for " + TypePath.GetAssemblyQualifiedName(family.PluginType); + string context = "Creating an InstanceInterceptor for " + + TypePath.GetAssemblyQualifiedName(family.PluginType); foreach (XmlNode interceptorNode in interceptorChainNode.ChildNodes) { XmlAttributeInstanceMemento interceptorMemento = new XmlAttributeInstanceMemento(interceptorNode); - _builder.WithSystemObject<IBuildInterceptor>(interceptorMemento, context, delegate(IBuildInterceptor interceptor) - { - family.AddInterceptor(interceptor); - }); - + _builder.WithSystemObject<IBuildInterceptor>(interceptorMemento, context, + delegate(IBuildInterceptor interceptor) { family.AddInterceptor(interceptor); }); } } } Modified: trunk/Source/StructureMap/Configuration/IGraphBuilder.cs =================================================================== --- trunk/Source/StructureMap/Configuration/IGraphBuilder.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/IGraphBuilder.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,5 +1,4 @@ using System; -using StructureMap.Attributes; using StructureMap.Graph; namespace StructureMap.Configuration @@ -30,5 +29,4 @@ void WithSystemObject<T>(InstanceMemento memento, string context, Action<T> action); void WithType(TypePath path, string context, Action<Type> action); } - } \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/ProfileAndMachineParser.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ProfileAndMachineParser.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/ProfileAndMachineParser.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,4 +1,3 @@ -using System; using System.Xml; using StructureMap.Graph; using StructureMap.Pipeline; @@ -9,9 +8,9 @@ // TODO: 3.5 cleanup public class ProfileAndMachineParser { - private readonly IProfileBuilder _profileBuilder; - private readonly IGraphBuilder _graphBuilder; private readonly XmlMementoCreator _creator; + private readonly IGraphBuilder _graphBuilder; + private readonly IProfileBuilder _profileBuilder; private readonly XmlNode _structureMapNode; public ProfileAndMachineParser(IGraphBuilder graphBuilder, XmlNode structureMapNode, XmlMementoCreator creator) @@ -91,9 +90,6 @@ family.AddInstance(memento); function(fullName, key); }); - - - } private XmlNodeList findNodes(string nodeName) Modified: trunk/Source/StructureMap/Configuration/ProfileBuilder.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ProfileBuilder.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/ProfileBuilder.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using StructureMap.Graph; using StructureMap.Pipeline; @@ -8,25 +6,11 @@ { public class ProfileBuilder : IProfileBuilder { - public static string GetMachineName() - { - string machineName = string.Empty; - try - { - machineName = Environment.MachineName.ToUpper(); - } - finally - { - } - - return machineName; - } - + private readonly string _machineName; private readonly PluginGraph _pluginGraph; - private readonly string _machineName; + private readonly ProfileManager _profileManager; private string _lastProfile; private bool _useMachineOverrides; - private readonly ProfileManager _profileManager; public ProfileBuilder(PluginGraph pluginGraph, string machineName) @@ -42,6 +26,8 @@ { } + #region IProfileBuilder Members + public void AddProfile(string profileName) { _lastProfile = profileName; @@ -81,5 +67,21 @@ { _profileManager.DefaultProfileName = profileName; } + + #endregion + + public static string GetMachineName() + { + string machineName = string.Empty; + try + { + machineName = Environment.MachineName.ToUpper(); + } + finally + { + } + + return machineName; + } } -} +} \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/XmlConstants.cs =================================================================== --- trunk/Source/StructureMap/Configuration/XmlConstants.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Configuration/XmlConstants.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,5 +1,3 @@ -using System; - namespace StructureMap.Configuration { /// <summary> Modified: trunk/Source/StructureMap/Diagnostics/Tokens.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/Tokens.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Diagnostics/Tokens.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -8,9 +8,9 @@ { public class GraphLog { - private List<Error> _errors = new List<Error>(); private readonly List<Source> _sources = new List<Source>(); private Source _currentSource; + private List<Error> _errors = new List<Error>(); public int ErrorCount { @@ -245,11 +245,6 @@ } - public int Code - { - get { return _code; } - } - public Error(StructureMapException exception) { _code = exception.ErrorCode; @@ -257,12 +252,12 @@ _stackTrace = exception.StackTrace; } - private string getMessage(int errorCode) + public int Code { - ResourceManager resources = new ResourceManager(typeof(StructureMapException)); - return resources.GetString(errorCode.ToString()); + get { return _code; } } + #region IEquatable<Error> Members public bool Equals(Error error) { @@ -276,6 +271,14 @@ return true; } + #endregion + + private string getMessage(int errorCode) + { + ResourceManager resources = new ResourceManager(typeof (StructureMapException)); + return resources.GetString(errorCode.ToString()); + } + public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; Modified: trunk/Source/StructureMap/Emitting/BuildInstanceMethod.cs =================================================================== --- trunk/Source/StructureMap/Emitting/BuildInstanceMethod.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Emitting/BuildInstanceMethod.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,7 +1,5 @@ using System; -using System.Reflection; using System.Reflection.Emit; -using StructureMap.Emitting.Parameters; using StructureMap.Graph; using StructureMap.Pipeline; @@ -33,7 +31,7 @@ public override Type[] ArgumentList { - get { return new Type[] { typeof(IConfiguredInstance), typeof(StructureMap.Pipeline.IBuildSession) }; } + get { return new Type[] {typeof (IConfiguredInstance), typeof (IBuildSession)}; } } public override string MethodName Modified: trunk/Source/StructureMap/Emitting/ClassBuilder.cs =================================================================== --- trunk/Source/StructureMap/Emitting/ClassBuilder.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Emitting/ClassBuilder.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -111,7 +111,7 @@ public void AddPluggedTypeGetter(Type pluggedType) { PropertyBuilder prop = - _newTypeBuilder.DefineProperty("PluggedType", PropertyAttributes.HasDefault, typeof(Type), null); + _newTypeBuilder.DefineProperty("PluggedType", PropertyAttributes.HasDefault, typeof (Type), null); MethodAttributes atts = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.SpecialName; @@ -119,19 +119,19 @@ string getterMethodName = "get_PluggedType"; MethodBuilder methodGet = - _newTypeBuilder.DefineMethod(getterMethodName, atts, CallingConventions.Standard, typeof(Type), null); + _newTypeBuilder.DefineMethod(getterMethodName, atts, CallingConventions.Standard, typeof (Type), null); ILGenerator gen = methodGet.GetILGenerator(); - LocalBuilder ilReturn = gen.DeclareLocal(typeof(Type)); + LocalBuilder ilReturn = gen.DeclareLocal(typeof (Type)); gen.Emit(OpCodes.Nop); gen.Emit(OpCodes.Ldtoken, pluggedType); - MethodInfo method = typeof(Type).GetMethod("GetTypeFromHandle"); + MethodInfo method = typeof (Type).GetMethod("GetTypeFromHandle"); gen.Emit(OpCodes.Call, method); gen.Emit(OpCodes.Stloc_0); - + gen.Emit(OpCodes.Ldloc_0); gen.Emit(OpCodes.Ret); Modified: trunk/Source/StructureMap/Emitting/InstanceBuilderAssembly.cs =================================================================== --- trunk/Source/StructureMap/Emitting/InstanceBuilderAssembly.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Emitting/InstanceBuilderAssembly.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -10,9 +10,9 @@ /// </summary> public class InstanceBuilderAssembly { + private readonly List<string> _classNames = new List<string>(); private readonly DynamicAssembly _dynamicAssembly; private readonly Type _pluginType; - private readonly List<string> _classNames = new List<string>(); public InstanceBuilderAssembly(Type pluginType, IEnumerable<Plugin> plugins) { @@ -86,10 +86,9 @@ { Assembly assembly = _dynamicAssembly.Compile(); - return _classNames.ConvertAll<InstanceBuilder>(delegate(string typeName) - { - return (InstanceBuilder) assembly.CreateInstance(typeName); - }); + return + _classNames.ConvertAll<InstanceBuilder>( + delegate(string typeName) { return (InstanceBuilder) assembly.CreateInstance(typeName); }); } Modified: trunk/Source/StructureMap/Emitting/Parameters/ChildArrayParameterEmitter.cs =================================================================== --- trunk/Source/StructureMap/Emitting/Parameters/ChildArrayParameterEmitter.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Emitting/Parameters/ChildArrayParameterEmitter.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,6 +1,7 @@ using System; using System.Reflection; using System.Reflection.Emit; +using StructureMap.Pipeline; namespace StructureMap.Emitting.Parameters { @@ -22,18 +23,18 @@ private void putChildArrayFromInstanceMementoOntoStack(ILGenerator ilgen, Type argumentType, string argumentName) { ilgen.Emit(OpCodes.Ldarg_2); - + //ilgen.Emit(OpCodes.Ldstr, argumentType.GetElementType().AssemblyQualifiedName); ilgen.Emit(OpCodes.Ldtoken, argumentType.GetElementType()); - MethodInfo method = typeof(Type).GetMethod("GetTypeFromHandle"); + MethodInfo method = typeof (Type).GetMethod("GetTypeFromHandle"); ilgen.Emit(OpCodes.Call, method); - + ilgen.Emit(OpCodes.Ldarg_1); ilgen.Emit(OpCodes.Ldstr, argumentName); callInstanceMemento(ilgen, "GetChildrenArray"); - MethodInfo methodCreateInstanceArray = (typeof (StructureMap.Pipeline.IBuildSession).GetMethod("CreateInstanceArray")); + MethodInfo methodCreateInstanceArray = (typeof (IBuildSession).GetMethod("CreateInstanceArray")); ilgen.Emit(OpCodes.Callvirt, methodCreateInstanceArray); cast(ilgen, argumentType); } Modified: trunk/Source/StructureMap/Emitting/Parameters/ParameterEmitter.cs =================================================================== --- trunk/Source/StructureMap/Emitting/Parameters/ParameterEmitter.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Emitting/Parameters/ParameterEmitter.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,7 +1,6 @@ using System; using System.Reflection; using System.Reflection.Emit; -using StructureMap.Graph; using StructureMap.Pipeline; namespace StructureMap.Emitting.Parameters @@ -22,6 +21,6 @@ protected void cast(ILGenerator ilgen, Type parameterType) { ilgen.Emit(OpCodes.Castclass, parameterType); - } + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Emitting/Parameters/StringParameterEmitter.cs =================================================================== --- trunk/Source/StructureMap/Emitting/Parameters/StringParameterEmitter.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Emitting/Parameters/StringParameterEmitter.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,4 +1,3 @@ -using System; using System.Reflection; using System.Reflection.Emit; Modified: trunk/Source/StructureMap/Graph/AssemblyScanner.cs =================================================================== --- trunk/Source/StructureMap/Graph/AssemblyScanner.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Graph/AssemblyScanner.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Reflection; -using System.Text; using StructureMap.Configuration.DSL; using StructureMap.Diagnostics; @@ -13,8 +12,8 @@ // TODO: redo in 3.5 w/ Lambdas public class AssemblyScanner { - private readonly GraphLog _log; private readonly List<Assembly> _assemblies = new List<Assembly>(); + private readonly GraphLog _log; public AssemblyScanner(GraphLog log) { @@ -33,7 +32,7 @@ { if (Registry.IsPublicRegistry(type)) { - Registry registry = (Registry)Activator.CreateInstance(type); + Registry registry = (Registry) Activator.CreateInstance(type); registry.ConfigurePluginGraph(pluginGraph); } }); @@ -45,12 +44,12 @@ private void findFamiliesAndPlugins(PluginGraph pluginGraph) { scanTypes(delegate(Type type) - { - if (PluginFamilyAttribute.MarkedAsPluginFamily(type)) - { - pluginGraph.CreateFamily(type); - } - }); + { + if (PluginFamilyAttribute.MarkedAsPluginFamily(type)) + { + pluginGraph.CreateFamily(type); + } + }); scanTypes(delegate(Type type) { @@ -69,7 +68,7 @@ private void scanTypes(Action<Type> action) { - scanTypes(new Action<Type>[]{action}); + scanTypes(new Action<Type>[] {action}); } private void scanTypes(IEnumerable<Action<Type>> actions) @@ -125,4 +124,4 @@ return false; } } -} +} \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/Constructor.cs =================================================================== --- trunk/Source/StructureMap/Graph/Constructor.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Graph/Constructor.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -5,6 +5,20 @@ { public class Constructor : TypeRules { + private readonly Type _pluggedType; + private ConstructorInfo _ctor; + + public Constructor(Type pluggedType) + { + _pluggedType = pluggedType; + _ctor = GetConstructor(pluggedType); + } + + public ConstructorInfo Ctor + { + get { return _ctor; } + } + /// <summary> /// Returns the System.Reflection.ConstructorInfo for the PluggedType. Uses either /// the "greediest" constructor with the most arguments or the constructor function @@ -48,16 +62,6 @@ return returnValue; } - - private readonly Type _pluggedType; - private ConstructorInfo _ctor; - - public Constructor(Type pluggedType) - { - _pluggedType = pluggedType; - _ctor = GetConstructor(pluggedType); - } - public bool CanBeAutoFilled() { foreach (ParameterInfo parameter in _ctor.GetParameters()) @@ -75,7 +79,7 @@ { foreach (ParameterInfo info in _ctor.GetParameters()) { - if (info.ParameterType.Equals(typeof(T))) + if (info.ParameterType.Equals(typeof (T))) { return info.Name; } @@ -85,11 +89,6 @@ } - public ConstructorInfo Ctor - { - get { return _ctor; } - } - public void Visit(IArgumentVisitor visitor) { foreach (ParameterInfo info in _ctor.GetParameters()) @@ -109,4 +108,4 @@ if (IsString(parameterType)) visitor.StringParameter(info); } } -} +} \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs =================================================================== --- trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -111,7 +111,7 @@ { if (instance.CanBePartOfPluginFamily(templatedFamily)) { - templatedFamily.AddInstance((Instance)instance); + templatedFamily.AddInstance((Instance) instance); } } @@ -122,7 +122,6 @@ } - public static Plugin CreateTemplatedClone(Plugin plugin, params Type[] types) { Type templatedType; Modified: trunk/Source/StructureMap/Graph/IPluginFamily.cs =================================================================== --- trunk/Source/StructureMap/Graph/IPluginFamily.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Graph/IPluginFamily.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -6,8 +6,6 @@ { public interface IPluginFamily { - void AddMementoSource(MementoSource source); - /// <summary> /// The InstanceKey of the default instance of the PluginFamily /// </summary> @@ -16,11 +14,10 @@ /// <summary> /// The CLR Type that defines the "Plugin" interface for the PluginFamily /// </summary> - Type PluginType - { - get; - } + Type PluginType { get; } + void AddMementoSource(MementoSource source); + void SetScopeTo(InstanceScope scope); void AddInterceptor(IBuildInterceptor interceptor); } Modified: trunk/Source/StructureMap/Graph/Plugin.cs =================================================================== --- trunk/Source/StructureMap/Graph/Plugin.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Graph/Plugin.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,6 +1,5 @@ using System; using System.Reflection; -using StructureMap.Emitting; using StructureMap.Pipeline; namespace StructureMap.Graph @@ -13,11 +12,11 @@ public class Plugin : TypeRules { public static readonly string DEFAULT = "DEFAULT"; + private readonly Constructor _constructor; - private string _concreteKey; private readonly Type _pluggedType; private readonly SetterPropertyCollection _setters; - private readonly Constructor _constructor; + private string _concreteKey; #region constructors @@ -44,7 +43,6 @@ #endregion - /// <summary> /// The ConcreteKey that identifies the Plugin within a PluginFamily /// </summary> @@ -68,18 +66,12 @@ /// </summary> public SetterPropertyCollection Setters { - get - { - return _setters; - } + get { return _setters; } } public bool CanBeAutoFilled { - get - { - return _constructor.CanBeAutoFilled() && _setters.CanBeAutoFilled(); - } + get { return _constructor.CanBeAutoFilled() && _setters.CanBeAutoFilled(); } } public override string ToString() @@ -95,13 +87,13 @@ public string FindFirstConstructorArgumentOfType<T>() { - string returnValue = + string returnValue = _constructor.FindFirstConstructorArgumentOfType<T>() ?? _setters.FindFirstConstructorArgumentOfType<T>(); if (returnValue == null) { - throw new StructureMapException(302, typeof(T).FullName, _pluggedType.FullName); + throw new StructureMapException(302, typeof (T).FullName, _pluggedType.FullName); } return returnValue; @@ -133,5 +125,4 @@ _setters.Visit(arguments); } } - } \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/PluginCollection.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginCollection.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Graph/PluginCollection.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -40,10 +40,7 @@ /// <returns></returns> public Plugin this[Type PluggedType] { - get - { - return _plugins[PluggedType]; - } + get { return _plugins[PluggedType]; } } /// <summary> @@ -67,6 +64,20 @@ } } + #region IEnumerable<Plugin> Members + + IEnumerator<Plugin> IEnumerable<Plugin>.GetEnumerator() + { + return _plugins.Values.GetEnumerator(); + } + + public IEnumerator GetEnumerator() + { + return ((IEnumerable<Plugin>) this).GetEnumerator(); + } + + #endregion + /// <summary> /// Adds a new Plugin by the PluggedType /// </summary> @@ -98,7 +109,8 @@ if (!TypeRules.CanBeCast(_family.PluginType, plugin.PluggedType)) { // TODO -- get this logged - throw new StructureMapException(114, plugin.PluggedType.FullName, _family.PluginType.AssemblyQualifiedName); + throw new StructureMapException(114, plugin.PluggedType.FullName, + _family.PluginType.AssemblyQualifiedName); } _plugins.Add(plugin.PluggedType, plugin); @@ -129,16 +141,6 @@ return plugin; } - IEnumerator<Plugin> IEnumerable<Plugin>.GetEnumerator() - { - return _plugins.Values.GetEnumerator(); - } - - public IEnumerator GetEnumerator() - { - return ((IEnumerable<Plugin>) this).GetEnumerator(); - } - public List<Plugin> FindAutoFillablePlugins() { List<Plugin> list = new List<Plugin>(); Modified: trunk/Source/StructureMap/Graph/PluginFamily.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginFamily.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Graph/PluginFamily.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,9 +1,6 @@ using System; -using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using StructureMap.Attributes; -using StructureMap.Interceptors; using StructureMap.Pipeline; namespace StructureMap.Graph @@ -15,16 +12,15 @@ /// </summary> public class PluginFamily : TypeRules, IPluginFamily { + private readonly Predicate<Type> _explicitlyMarkedPluginFilter; + private readonly Predicate<Type> _implicitPluginFilter; + private readonly List<Instance> _instances = new List<Instance>(); private readonly List<InstanceMemento> _mementoList = new List<InstanceMemento>(); private readonly PluginCollection _plugins; + private readonly Type _pluginType; + private IBuildPolicy _buildPolicy = new BuildPolicy(); private string _defaultKey = string.Empty; private PluginGraph _parent; - private readonly List<Instance> _instances = new List<Instance>(); - private IBuildPolicy _buildPolicy = new BuildPolicy(); - private readonly Type _pluginType; - - private readonly Predicate<Type> _explicitlyMarkedPluginFilter; - private readonly Predicate<Type> _implicitPluginFilter; private Predicate<Type> _pluginFilter; private IBuildPolicy _policy; @@ -35,8 +31,8 @@ PluginFamilyAttribute.ConfigureFamily(this); - _explicitlyMarkedPluginFilter = delegate(Type type) { return TypeRules.IsExplicitlyMarkedAsPlugin(PluginType, type); }; - _implicitPluginFilter = delegate(Type type) { return TypeRules.CanBeCast(PluginType, type); }; + _explicitlyMarkedPluginFilter = delegate(Type type) { return IsExplicitlyMarkedAsPlugin(PluginType, type); }; + _implicitPluginFilter = delegate(Type type) { return CanBeCast(PluginType, type); }; _pluginFilter = _explicitlyMarkedPluginFilter; if (IsConcrete(pluginType)) @@ -53,91 +49,69 @@ set { _parent = value; } } - public void AddInstance(InstanceMemento memento) - { - _mementoList.Add(memento); - } + #region IPluginFamily Members - public void AddInstance(Instance instance) - { - _instances.Add(instance); - } - - // TODO -- eliminate this. Move to GraphBuilder, and wrap error handling around it public void AddMementoSource(MementoSource source) { _mementoList.AddRange(source.GetAllMementos()); } - // For testing - public InstanceMemento GetMemento(string instanceKey) + public void SetScopeTo(InstanceScope scope) { - return _mementoList.Find(delegate(InstanceMemento m) { return m.InstanceKey == instanceKey; }); - } + switch (scope) + { + case InstanceScope.Singleton: + AddInterceptor(new SingletonPolicy()); + break; + case InstanceScope.HttpContext: + AddInterceptor(new HttpContextBuildPolicy()); + break; + case InstanceScope.ThreadLocal: + AddInterceptor(new ThreadLocalStoragePolicy()); + break; - #region properties - - /// <summary> - /// The CLR Type that defines the "Plugin" interface for the PluginFamily - /// </summary> - public Type PluginType - { - get { return _pluginType; } + case InstanceScope.Hybrid: + AddInterceptor(new HybridBuildPolicy()); + break; + } } - /// <summary> - /// The InstanceKey of the default instance of the PluginFamily - /// </summary> - public string DefaultInstanceKey + public void AddInterceptor(IBuildInterceptor interceptor) { - get { return _defaultKey; } - set { _defaultKey = value ?? string.Empty; } + interceptor.InnerPolicy = _buildPolicy; + _buildPolicy = interceptor; } - public PluginCollection Plugins - { - get { return _plugins; } - } + #endregion - public bool IsGenericTemplate + public void AddInstance(InstanceMemento memento) { - get { return _pluginType.IsGenericTypeDefinition; } + _mementoList.Add(memento); } - public bool SearchForImplicitPlugins + public void AddInstance(Instance instance) { - get - { - return ReferenceEquals(_pluginFilter, _implicitPluginFilter); - } - set - { - _pluginFilter = value ? _implicitPluginFilter : _explicitlyMarkedPluginFilter; - } + _instances.Add(instance); } - public IBuildPolicy Policy - { - get { return _buildPolicy; } - set { _policy = value; } - } + // TODO -- eliminate this. Move to GraphBuilder, and wrap error handling around it - public int PluginCount + // For testing + public InstanceMemento GetMemento(string instanceKey) { - get { return _plugins.Count; } + return _mementoList.Find(delegate(InstanceMemento m) { return m.InstanceKey == instanceKey; }); } - #endregion public void Seal() { _mementoList.ForEach(delegate(InstanceMemento memento) - { - Instance instance = memento.ReadInstance(Parent, _pluginType); - _instances.Add(instance); - }); + { + Instance instance = memento.ReadInstance(Parent, _pluginType); + _instances.Add(instance); + }); discoverImplicitInstances(); @@ -151,13 +125,8 @@ { // TODO: Apply some 3.5 lambda magic. Maybe move to PluginCollection List<Plugin> list = _plugins.FindAutoFillablePlugins(); - list.RemoveAll(delegate(Plugin plugin) - { - return _instances.Exists(delegate(Instance instance) - { - return instance.Matches(plugin); - }); - }); + list.RemoveAll( + delegate(Plugin plugin) { return _instances.Exists(delegate(Instance instance) { return instance.Matches(plugin); }); }); foreach (Plugin plugin in list) { @@ -175,35 +144,7 @@ return _instances.Find(delegate(Instance i) { return i.Name == name; }); } - public void SetScopeTo(InstanceScope scope) - { - switch(scope) - { - case InstanceScope.Singleton: - AddInterceptor(new SingletonPolicy()); - break; - case InstanceScope.HttpContext: - AddInterceptor(new HttpContextBuildPolicy()); - break; - - case InstanceScope.ThreadLocal: - AddInterceptor(new ThreadLocalStoragePolicy()); - break; - - case InstanceScope.Hybrid: - AddInterceptor(new HybridBuildPolicy()); - break; - } - } - - public void AddInterceptor(IBuildInterceptor interceptor) - { - interceptor.InnerPolicy = _buildPolicy; - _buildPolicy = interceptor; - } - - public void AnalyzeTypeForPlugin(Type pluggedType) { if (_pluginFilter(pluggedType)) @@ -246,5 +187,53 @@ { return string.IsNullOrEmpty(_defaultKey) ? null : GetInstance(_defaultKey); } + + #region properties + + public PluginCollection Plugins + { + get { return _plugins; } + } + + public bool IsGenericTemplate + { + get { return _pluginType.IsGenericTypeDefinition; } + } + + public bool SearchForImplicitPlugins + { + get { return ReferenceEquals(_pluginFilter, _implicitPluginFilter); } + set { _pluginFilter = value ? _implicitPluginFilter : _explicitlyMarkedPluginFilter; } + } + + public IBuildPolicy Policy + { + get { return _buildPolicy; } + set { _policy = value; } + } + + public int PluginCount + { + get { return _plugins.Count; } + } + + /// <summary> + /// The CLR Type that defines the "Plugin" interface for the PluginFamily + /// </summary> + public Type PluginType + { + get { return _pluginType; } + } + + /// <summary> + /// The InstanceKey of the default instance of the PluginFamily + /// </summary> + public string DefaultInstanceKey + { + get { return _defaultKey; } + set { _defaultKey = value ?? string.Empty; } + } + + #endregion } } \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/PluginFamilyCollection.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginFamilyCollection.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Graph/PluginFamilyCollection.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -9,8 +9,8 @@ /// </summary> public class PluginFamilyCollection : IEnumerable<PluginFamily> { + private readonly Dictionary<Type, PluginFamily> _pluginFamilies; private readonly PluginGraph _pluginGraph; - private readonly Dictionary<Type, PluginFamily> _pluginFamilies; public PluginFamilyCollection(PluginGraph pluginGraph) { @@ -37,7 +37,20 @@ get { return _pluginFamilies.Count; } } + #region IEnumerable<PluginFamily> Members + IEnumerator<PluginFamily> IEnumerable<PluginFamily>.GetEnumerator() + { + return _pluginFamilies.Values.GetEnumerator(); + } + + public IEnumerator GetEnumerator() + { + return ((IEnumerable<PluginFamily>) this).GetEnumerator(); + } + + #endregion + public PluginFamily Add(PluginFamily family) { family.Parent = _pluginGraph; @@ -69,17 +82,5 @@ { return Contains(typeof (T)); } - - - - IEnumerator<PluginFamily> IEnumerable<PluginFamily>.GetEnumerator() - { - return _pluginFamilies.Values.GetEnumerator(); - } - - public IEnumerator GetEnumerator() - { - return ((IEnumerable<PluginFamily>) this).GetEnumerator(); - } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/SetterPropertyCollection.cs =================================================================== --- trunk/Source/StructureMap/Graph/SetterPropertyCollection.cs 2008-05-15 16:32:20 UTC (rev 96) +++ trunk/Source/StructureMap/Graph/SetterPropertyCollection.cs 2008-05-15 18:15:44 UTC (rev 97) @@ -1,7 +1,5 @@ -using System; using System.Collections; using System.Collections.Generic; -using System.Collections.Specialized; using System.Reflection; using StructureMap.Attributes; @@ -34,7 +32,7 @@ { SetterProperty[] returnValue = new SetterProperty[_properties.Count]; _properties.Values.CopyTo(returnValue, 0); - + ... [truncated message content] |
From: <jer...@us...> - 2008-05-17 01:25:22
|
Revision: 98 http://structuremap.svn.sourceforge.net/structuremap/?rev=98&view=rev Author: jeremydmiller Date: 2008-05-16 18:25:16 -0700 (Fri, 16 May 2008) Log Message: ----------- Putting WhatDoIHave back together, diagnostics fixes, rewrote InlineInstanceDefinitionInProfileAndMachineNodesTester, rewrote unit tests for error handling, made BuildSession cache instances Modified Paths: -------------- trunk/Source/CommonAssemblyInfo.cs trunk/Source/StructureMap/BuildSession.cs trunk/Source/StructureMap/Configuration/ConfigurationParser.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs trunk/Source/StructureMap/Configuration/DSL/Registry.cs trunk/Source/StructureMap/Configuration/FamilyParser.cs trunk/Source/StructureMap/Configuration/GraphBuilder.cs trunk/Source/StructureMap/Configuration/ProfileBuilder.cs trunk/Source/StructureMap/Configuration/StructureMapConfigurationSection.cs trunk/Source/StructureMap/Diagnostics/Tokens.cs trunk/Source/StructureMap/Graph/Constructor.cs trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs trunk/Source/StructureMap/Graph/PluginCollection.cs trunk/Source/StructureMap/Graph/PluginFamily.cs trunk/Source/StructureMap/Graph/PluginFamilyCollection.cs trunk/Source/StructureMap/Graph/PluginGraph.cs trunk/Source/StructureMap/IInstanceFactory.cs trunk/Source/StructureMap/IInstanceManager.cs trunk/Source/StructureMap/InstanceFactory.cs trunk/Source/StructureMap/InstanceManager.cs trunk/Source/StructureMap/InstanceMemento.cs trunk/Source/StructureMap/ObjectFactory.cs trunk/Source/StructureMap/Pipeline/CacheInterceptor.cs trunk/Source/StructureMap/Pipeline/ConfiguredInstance.cs trunk/Source/StructureMap/Pipeline/ConstructorInstance.cs trunk/Source/StructureMap/Pipeline/DefaultInstance.cs trunk/Source/StructureMap/Pipeline/Instance.cs trunk/Source/StructureMap/Pipeline/LiteralInstance.cs trunk/Source/StructureMap/Pipeline/Profile.cs trunk/Source/StructureMap/Pipeline/PrototypeInstance.cs trunk/Source/StructureMap/Pipeline/ReferencedInstance.cs trunk/Source/StructureMap/Pipeline/UserControlInstance.cs trunk/Source/StructureMap/PipelineGraph.cs trunk/Source/StructureMap/PluginGraphBuilder.cs trunk/Source/StructureMap/Source/XmlNodeInstanceMemento.cs trunk/Source/StructureMap/StructureMap.csproj trunk/Source/StructureMap/StructureMapConfiguration.cs trunk/Source/StructureMap/StructureMapException.resx trunk/Source/StructureMap.Testing/BuildSessionTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/ConstructorExpressionTester.cs trunk/Source/StructureMap.Testing/Configuration/InlineInstanceDefinitionInProfileAndMachineNodesTester.cs trunk/Source/StructureMap.Testing/Container/ArrayConstructorTester.cs trunk/Source/StructureMap.Testing/Container/DynamicInjectionTester.cs trunk/Source/StructureMap.Testing/Container/ExceptionHandling/StructureMapExceptionTester.cs trunk/Source/StructureMap.Testing/Container/InstanceFactoryTester.cs trunk/Source/StructureMap.Testing/Container/Interceptors/TypeInterceptionTester.cs trunk/Source/StructureMap.Testing/Graph/PluginFamilyTester.cs trunk/Source/StructureMap.Testing/Graph/PluginGraphTester.cs trunk/Source/StructureMap.Testing/Graph/SetterInjectionTester.cs trunk/Source/StructureMap.Testing/ObjectFactoryTester.cs trunk/Source/StructureMap.Testing/Pipeline/BuildStrategiesTester.cs trunk/Source/StructureMap.Testing/Pipeline/ConfiguredInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/DefaultInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/InstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/LiteralInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/ProfileManagerTester.cs trunk/Source/StructureMap.Testing/Pipeline/ProfileTester.cs trunk/Source/StructureMap.Testing/Pipeline/PrototypeInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/ReferencedInstanceTester.cs trunk/Source/StructureMap.Testing/StructureMap.Testing.csproj trunk/Source/StructureMap.Testing/StructureMapConfigurationTester.cs trunk/Source/StructureMap.Testing/TestData/DataMother.cs Added Paths: ----------- trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs trunk/Source/StructureMap/Diagnostics/CharacterWidth.cs trunk/Source/StructureMap/Diagnostics/DividerLine.cs trunk/Source/StructureMap/Diagnostics/Line.cs trunk/Source/StructureMap/Diagnostics/TextLine.cs trunk/Source/StructureMap/Diagnostics/TextReportWriter.cs trunk/Source/StructureMap/Diagnostics/WhatDoIHaveWriter.cs trunk/Source/StructureMap/InstanceCache.cs trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserBuilderTester.cs trunk/Source/StructureMap.Testing/Diagnostics/ trunk/Source/StructureMap.Testing/Diagnostics/TextReportWriterSmokeTester.cs trunk/Source/StructureMap.Testing/PipelineGraphTester.cs trunk/Source/StructureMap.Testing/TestUtility.cs Removed Paths: ------------- trunk/Source/StructureMap/Configuration/ConfigurationParserCollection.cs trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserCollectionTester.cs trunk/Source/StructureMap.Testing/Container/ExceptionHandling/ExceptionTestRunner.cs trunk/Source/StructureMap.Testing/TestData/ExceptionHandlingTests.xml trunk/Source/StructureMap.Testing/TestData/InlineInstanceInProfileAndMachine.xml Modified: trunk/Source/CommonAssemblyInfo.cs =================================================================== --- trunk/Source/CommonAssemblyInfo.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/CommonAssemblyInfo.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -1,3 +1,4 @@ +using System; using System.Reflection; using System.Runtime.InteropServices; @@ -11,10 +12,11 @@ // </auto-generated> //------------------------------------------------------------------------------ -[assembly : ComVisible(false)] -[assembly : AssemblyVersion("2.5.0.0000")] -[assembly : AssemblyCopyrightAttribute("Copyright (c) 2007, Jeremy D. Miller")] -[assembly : AssemblyProductAttribute("StructureMap")] -[assembly : AssemblyCompanyAttribute("")] -[assembly : AssemblyConfigurationAttribute("release")] -[assembly : AssemblyInformationalVersionAttribute("2.5.0.0000")] \ No newline at end of file +[assembly: ComVisibleAttribute(false)] +[assembly: AssemblyVersionAttribute("2.5.0.0000")] +[assembly: AssemblyCopyrightAttribute("Copyright (c) 2007, Jeremy D. Miller")] +[assembly: AssemblyProductAttribute("StructureMap")] +[assembly: AssemblyCompanyAttribute("")] +[assembly: AssemblyConfigurationAttribute("release")] +[assembly: AssemblyInformationalVersionAttribute("2.5.0.0000")] + Modified: trunk/Source/StructureMap/BuildSession.cs =================================================================== --- trunk/Source/StructureMap/BuildSession.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/BuildSession.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using StructureMap.Graph; using StructureMap.Interceptors; using StructureMap.Pipeline; @@ -8,6 +10,7 @@ { private readonly InterceptorLibrary _interceptorLibrary; private readonly PipelineGraph _pipelineGraph; + private InstanceCache _cache = new InstanceCache(); public BuildSession(PipelineGraph pipelineGraph, InterceptorLibrary interceptorLibrary) { @@ -15,16 +18,36 @@ _interceptorLibrary = interceptorLibrary; } + public BuildSession(PluginGraph graph) + : this(new PipelineGraph(graph), graph.InterceptorLibrary) + { + + } + #region IBuildSession Members - public object CreateInstance(Type type, string name) + public object CreateInstance(Type pluginType, string name) { - return forType(type).Build(this, name); + Instance instance = forType(pluginType).FindInstance(name); + if (instance == null) + { + throw new StructureMapException(200, name, pluginType.FullName); + } + + return CreateInstance(pluginType, instance); } public object CreateInstance(Type pluginType, Instance instance) { - return forType(pluginType).Build(this, instance); + object result = _cache.Get(pluginType, instance); + + if (result == null) + { + result = forType(pluginType).Build(this, instance); + _cache.Set(pluginType, instance, result); + } + + return result; } public Array CreateInstanceArray(Type pluginType, Instance[] instances) @@ -57,7 +80,7 @@ throw new StructureMapException(202, pluginType.FullName); } - return forType(pluginType).Build(this, instance); + return CreateInstance(pluginType, instance); } public object ApplyInterception(Type pluginType, object actualValue) Modified: trunk/Source/StructureMap/Configuration/ConfigurationParser.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ConfigurationParser.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Configuration/ConfigurationParser.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Xml; +using StructureMap.Diagnostics; using StructureMap.Graph; using StructureMap.Source; @@ -11,76 +12,28 @@ { #region statics - public static ConfigurationParser[] GetParsers(XmlDocument document, string includePath) - { - XmlElement node = document.DocumentElement; - return GetParsers(node, includePath); - } - - // TODO -- Clean up. Maybe use some Lambda magic with .Net 3.5? - public static ConfigurationParser[] GetParsers(XmlNode node, string includePath) - { - string folder = string.IsNullOrEmpty(includePath) ? string.Empty : Path.GetDirectoryName(includePath); - - List<ConfigurationParser> list = new List<ConfigurationParser>(); - - list.Add(new ConfigurationParser(node)); - - string includedPath = null; - - try - { - XmlNodeList includeNodes = node.SelectNodes(XmlConstants.INCLUDE_NODE); - foreach (XmlElement includeElement in includeNodes) - { - XmlDocument includedDoc = new XmlDocument(); - string fileName = includeElement.GetAttribute("File"); - - if (fileName == string.Empty) - { - // TODO: get rid of throw, put on PluginGraph here - throw new ApplicationException("The File attribute on the Include node is required"); - } - - try - { - includedPath = Path.Combine(folder, fileName); - includedDoc.Load(includedPath); - - - ConfigurationParser parser = new ConfigurationParser(includedDoc.DocumentElement); - list.Add(parser); - } - catch (Exception ex) - { - // TODO: get rid of throw, put on PluginGraph here - throw new StructureMapException(150, ex, fileName); - } - } - } - catch (Exception ex) - { - // TODO: get rid of throw, put on PluginGraph here - throw new StructureMapException(100, includedPath, ex); - } - - return list.ToArray(); - } - - public static ConfigurationParser FromFile(string filename) { XmlDocument document = new XmlDocument(); document.Load(filename); XmlNode structureMapNode = document.SelectSingleNode("//" + XmlConstants.STRUCTUREMAP); - return new ConfigurationParser(structureMapNode); + if (structureMapNode == null) + { + throw new StructureMapException(155, filename); + } + + ConfigurationParser parser = new ConfigurationParser(structureMapNode); + parser.FilePath = filename; + + return parser; } #endregion private readonly XmlMementoCreator _mementoCreator; private readonly XmlNode _structureMapNode; + private string _filePath = string.Empty; public ConfigurationParser(XmlNode structureMapNode) { @@ -106,6 +59,36 @@ XmlConstants.KEY_ATTRIBUTE); } + public void ForEachFile(GraphLog log, Action<string> action) + { + // TODO: Clean up with 3.5 + string includePath = getIncludePath(); + XmlNodeList includeNodes = _structureMapNode.SelectNodes(XmlConstants.INCLUDE_NODE); + foreach (XmlElement includeElement in includeNodes) + { + string fileName = includeElement.GetAttribute("File"); + if (string.IsNullOrEmpty(fileName)) + { + log.RegisterError(156, _filePath); + } + else + { + string includedFile = Path.Combine(includePath, fileName); + action(includedFile); + } + } + } + + private string getIncludePath() + { + if (string.IsNullOrEmpty(_filePath)) + { + return string.Empty; + } + + return Path.GetDirectoryName(_filePath); + } + public string Id { get @@ -115,6 +98,13 @@ } } + + public string FilePath + { + get { return _filePath; } + set { _filePath = value; } + } + public void ParseAssemblies(IGraphBuilder builder) { parseAssemblies(builder); Added: trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs (rev 0) +++ trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Xml; +using StructureMap.Diagnostics; + +namespace StructureMap.Configuration +{ + public class ConfigurationParserBuilder + { + private readonly List<XmlNode> _nodes = new List<XmlNode>(); + private readonly List<string> _otherFiles = new List<string>(); + private bool _ignoreDefaultFile = false; + private readonly GraphLog _log; + private bool _useAndEnforceExistenceOfDefaultFile = false; + private bool _pullConfigurationFromAppConfig; + + + public ConfigurationParserBuilder(GraphLog log) + { + _log = log; + } + + public bool UseAndEnforceExistenceOfDefaultFile + { + get { return _useAndEnforceExistenceOfDefaultFile; } + set { _useAndEnforceExistenceOfDefaultFile = value; } + } + + + public bool IgnoreDefaultFile + { + get { return _ignoreDefaultFile; } + set { _ignoreDefaultFile = value; } + } + + public bool PullConfigurationFromAppConfig + { + get { return _pullConfigurationFromAppConfig; } + set + { + _pullConfigurationFromAppConfig = value; + } + } + + // TODO: Clean up with 3.5 + public ConfigurationParser[] GetParsers() + { + List<ConfigurationParser> list = new List<ConfigurationParser>(); + + // Pick up the configuration in the default StructureMap.config + string pathToStructureMapConfig = StructureMapConfiguration.GetStructureMapConfigurationPath(); + if (shouldUseStructureMapConfigFileAt(pathToStructureMapConfig)) + { + _log.Try(delegate() + { + ConfigurationParser parser = ConfigurationParser.FromFile(pathToStructureMapConfig); + list.Add(parser); + }).AndReportErrorAs(100, pathToStructureMapConfig); + } + + foreach (string filename in _otherFiles) + { + _log.Try(delegate() + { + ConfigurationParser parser = ConfigurationParser.FromFile(filename); + list.Add(parser); + }).AndReportErrorAs(160, filename); + } + + if (_pullConfigurationFromAppConfig) + { + _log.Try(delegate() + { + IList<XmlNode> appConfigNodes = StructureMapConfigurationSection.GetStructureMapConfiguration(); + foreach (XmlNode appConfigNode in appConfigNodes) + { + IncludeNode(appConfigNode); + } + }).AndLogAnyErrors(); + + } + + // TODO -- some error handling here, or somewhere else. Need to create ConfigurationParser + // as soon as the node is added to try to determine errors + foreach (XmlNode node in _nodes) + { + ConfigurationParser parser = new ConfigurationParser(node); + list.Add(parser); + } + + foreach (ConfigurationParser parser in list.ToArray()) + { + parser.ForEachFile(_log, + delegate(string filename) + { + _log.Try(delegate() + { + ConfigurationParser childParser = ConfigurationParser.FromFile(filename); + list.Add(childParser); + }).AndReportErrorAs(150, filename); + }); + } + + + return list.ToArray(); + } + + private bool shouldUseStructureMapConfigFileAt(string pathToStructureMapConfig) + { + return + (_useAndEnforceExistenceOfDefaultFile || + File.Exists(pathToStructureMapConfig)) && !_ignoreDefaultFile; + } + + + public void IncludeFile(string filename) + { + _otherFiles.Add(filename); + } + + public void IncludeNode(XmlNode node) + { + _nodes.Add(node); + } + + public static ConfigurationParser[] GetParsers(XmlNode node, GraphLog log) + { + ConfigurationParserBuilder builder = new ConfigurationParserBuilder(log); + builder.IncludeNode(node); + builder.IgnoreDefaultFile = true; + + return builder.GetParsers(); + } + } +} \ No newline at end of file Deleted: trunk/Source/StructureMap/Configuration/ConfigurationParserCollection.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ConfigurationParserCollection.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Configuration/ConfigurationParserCollection.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -1,95 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml; - -namespace StructureMap.Configuration -{ - // TODO: 3.5 cleanup here - public delegate XmlNode FetchNodeDelegate(); - - public class ConfigurationParserCollection - { - private readonly List<FetchNodeDelegate> _fetchers = new List<FetchNodeDelegate>(); - private readonly List<string> _otherFiles = new List<string>(); - private bool _ignoreDefaultFile = false; - private bool _useAndEnforceExistenceOfDefaultFile = false; - - public bool UseAndEnforceExistenceOfDefaultFile - { - get { return _useAndEnforceExistenceOfDefaultFile; } - set { _useAndEnforceExistenceOfDefaultFile = value; } - } - - - public bool IgnoreDefaultFile - { - get { return _ignoreDefaultFile; } - set { _ignoreDefaultFile = value; } - } - - public ConfigurationParser[] GetParsers() - { - List<ConfigurationParser> list = new List<ConfigurationParser>(); - - // Pick up the configuration in the default StructureMap.config - string pathToStructureMapConfig = StructureMapConfiguration.GetStructureMapConfigurationPath(); - if (shouldUseStructureMapConfigFile(pathToStructureMapConfig)) - { - addParsersFromFile(pathToStructureMapConfig, list); - } - - foreach (string file in _otherFiles) - { - addParsersFromFile(file, list); - } - - foreach (FetchNodeDelegate fetcher in _fetchers) - { - XmlNode node = fetcher(); - addParsersFromDocument(node, string.Empty, list); - } - - return list.ToArray(); - } - - private bool shouldUseStructureMapConfigFile(string pathToStructureMapConfig) - { - return - (_useAndEnforceExistenceOfDefaultFile || File.Exists(pathToStructureMapConfig)) && !_ignoreDefaultFile; - } - - private static void addParsersFromFile(string filename, List<ConfigurationParser> list) - { - try - { - XmlDocument doc = new XmlDocument(); - doc.Load(filename); - - string includePath = Path.GetDirectoryName(filename); - addParsersFromDocument(doc.DocumentElement, includePath, list); - } - catch (Exception ex) - { - // TODO -- needs to log to PluginGraph instead - throw new StructureMapException(100, filename, ex); - } - } - - private static void addParsersFromDocument(XmlNode node, string includePath, List<ConfigurationParser> list) - { - ConfigurationParser[] parsers = ConfigurationParser.GetParsers(node, includePath); - list.AddRange(parsers); - } - - public void IncludeFile(string filename) - { - _otherFiles.Add(filename); - } - - public void IncludeNode(FetchNodeDelegate fetcher) - { - _fetchers.Add(fetcher); - } - } -} \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -37,6 +37,11 @@ #endregion // TODO: 3.5, Try alterAndContinue(f => {}); + private CreatePluginFamilyExpression<PLUGINTYPE> alterAndContinue(Action<PluginFamily> action) + { + _alterations.Add(action); + return this; + } /// <summary> /// Sets the default instance of a Type to the definition represented by builder @@ -45,21 +50,17 @@ /// <returns></returns> public CreatePluginFamilyExpression<PLUGINTYPE> TheDefaultIs(Instance instance) { - _alterations.Add(delegate(PluginFamily family) + return alterAndContinue(delegate(PluginFamily family) { family.AddInstance(instance); family.DefaultInstanceKey = instance.Name; }); - - return this; } public CreatePluginFamilyExpression<PLUGINTYPE> AddInstance(Instance instance) { - // TODO: Validate pluggability - _alterations.Add(delegate(PluginFamily family) { family.AddInstance(instance); }); - - return this; + return alterAndContinue( + delegate(PluginFamily family) { family.AddInstance(instance); }); } /// <summary> @@ -74,9 +75,9 @@ { ExpressionValidator.ValidatePluggabilityOf(typeof (CONCRETETYPE)).IntoPluginType(_pluginType); - _alterations.Add(delegate(PluginFamily family) + return alterAndContinue(delegate(PluginFamily family) { - Plugin plugin = family.Plugins.FindOrCreate(typeof (CONCRETETYPE), true); + Plugin plugin = family.Plugins.FindOrCreate(typeof(CONCRETETYPE), true); family.DefaultInstanceKey = plugin.ConcreteKey; }); @@ -91,9 +92,7 @@ /// <returns></returns> public CreatePluginFamilyExpression<PLUGINTYPE> CacheBy(InstanceScope scope) { - _alterations.Add(delegate(PluginFamily family) { family.SetScopeTo(scope); }); - - return this; + return alterAndContinue(delegate(PluginFamily family) { family.SetScopeTo(scope); }); } /// <summary> @@ -147,6 +146,8 @@ public CreatePluginFamilyExpression<PLUGINTYPE> AddConcreteType<CONCRETETYPE>(string instanceName) { + ExpressionValidator.ValidatePluggabilityOf(typeof(CONCRETETYPE)).IntoPluginType(typeof(PLUGINTYPE)); + _alterations.Add( delegate(PluginFamily family) { @@ -174,6 +175,8 @@ public CreatePluginFamilyExpression<PLUGINTYPE> AliasConcreteType<PLUGGEDTYPE>(string concreteKey) { + ExpressionValidator.ValidatePluggabilityOf(typeof(PLUGGEDTYPE)).IntoPluginType(typeof(PLUGINTYPE)); + _alterations.Add(delegate(PluginFamily family) { family.AddPlugin(typeof (PLUGGEDTYPE), concreteKey); }); return this; Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -33,21 +33,27 @@ internal void Configure(string profileName, PluginGraph pluginGraph) { + // The profile instance is defined inline if (_instance != null) { _instanceKey = Profile.InstanceKeyForProfile(profileName); _instance.Name = _instanceKey; pluginGraph.FindFamily(_pluginType).AddInstance(_instance); } + + // Using a referenced key for the profile else if (!string.IsNullOrEmpty(_instanceKey)) { _instance = new ReferencedInstance(_instanceKey); } + // Set the default instance in the Profile if (_instance != null) { pluginGraph.ProfileManager.SetDefault(profileName, _pluginType, _instance); } + + // Blow up if the Profile expression is not complete. else { throw new StructureMapException(304, TypePath.GetAssemblyQualifiedName(_pluginType)); @@ -61,6 +67,8 @@ /// <returns></returns> public ProfileExpression Use(Instance instance) { + // TODO -- validate that the instance can be plugged into the PluginType + _instance = instance; return _parent; Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -73,7 +73,6 @@ public ScanAssembliesExpression AddAllTypesOf<PLUGINTYPE>() { - // TODO: Do this by adding something to TypeScanner _registry.addExpression(delegate(PluginGraph pluginGraph) { PluginFamily family = Modified: trunk/Source/StructureMap/Configuration/DSL/Registry.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -238,9 +238,9 @@ } public static ConstructorInstance ConstructedBy<PLUGINTYPE> - (BuildObjectDelegate builder) + (Func<PLUGINTYPE> builder) { - return new ConstructorInstance(builder); + return new ConstructorInstance(delegate() { return builder(); }); } public static ReferencedInstance Instance(string referencedKey) Modified: trunk/Source/StructureMap/Configuration/FamilyParser.cs =================================================================== --- trunk/Source/StructureMap/Configuration/FamilyParser.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Configuration/FamilyParser.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -22,17 +22,17 @@ { TypePath typePath = TypePath.CreateFromXmlNode(familyElement); _builder.ConfigureFamily(typePath, delegate(PluginFamily family) - { - family.DefaultInstanceKey = - familyElement.GetAttribute(XmlConstants.DEFAULT_KEY_ATTRIBUTE); + { + family.DefaultInstanceKey = + familyElement.GetAttribute(XmlConstants.DEFAULT_KEY_ATTRIBUTE); - InstanceScope scope = findScope(familyElement); - family.SetScopeTo(scope); + InstanceScope scope = findScope(familyElement); + family.SetScopeTo(scope); - attachMementoSource(family, familyElement); - attachPlugins(family, familyElement); - attachInterceptors(family, familyElement); - }); + attachMementoSource(family, familyElement); + attachPlugins(family, familyElement); + attachInterceptors(family, familyElement); + }); } public void ParseDefaultElement(XmlElement element) @@ -40,28 +40,27 @@ TypePath pluginTypePath = new TypePath(element.GetAttribute(XmlConstants.PLUGIN_TYPE)); - _builder.ConfigureFamily(pluginTypePath, - delegate(PluginFamily family) - { - // TODO: there's a little duplication here - InstanceScope scope = findScope(element); - family.SetScopeTo(scope); + _builder.ConfigureFamily(pluginTypePath, delegate(PluginFamily family) + { + // TODO: there's a little duplication here + InstanceScope scope = findScope(element); + family.SetScopeTo(scope); - Type pluginType = family.PluginType; + Type pluginType = family.PluginType; - string name = element.GetAttribute(XmlConstants.NAME); - if (string.IsNullOrEmpty(name)) - { - name = "DefaultInstanceOf" + pluginTypePath.AssemblyQualifiedName; - } + string name = element.GetAttribute(XmlConstants.NAME); + if (string.IsNullOrEmpty(name)) + { + name = "DefaultInstanceOf" + pluginTypePath.AssemblyQualifiedName; + } - InstanceMemento memento = _mementoCreator.CreateMemento(element); - memento.InstanceKey = name; + InstanceMemento memento = _mementoCreator.CreateMemento(element); + memento.InstanceKey = name; - family.DefaultInstanceKey = name; + family.DefaultInstanceKey = name; - family.AddInstance(memento); - }); + family.AddInstance(memento); + }); } public void ParseInstanceElement(XmlElement element) @@ -69,11 +68,11 @@ TypePath pluginTypePath = new TypePath(element.GetAttribute(XmlConstants.PLUGIN_TYPE)); _builder.ConfigureFamily(pluginTypePath, delegate(PluginFamily family) - { - InstanceMemento memento = - _mementoCreator.CreateMemento(element); - family.AddInstance(memento); - }); + { + InstanceMemento memento = + _mementoCreator.CreateMemento(element); + family.AddInstance(memento); + }); } private InstanceScope findScope(XmlElement familyElement) @@ -97,7 +96,8 @@ { InstanceMemento sourceMemento = new XmlAttributeInstanceMemento(sourceNode); - string context = "MementoSource for " + TypePath.GetAssemblyQualifiedName(family.PluginType); + string context = "MementoSource for " + TypePath.GetAssemblyQualifiedName(family.PluginType) + "\n" + + sourceNode.OuterXml; _builder.WithSystemObject<MementoSource>(sourceMemento, context, delegate(MementoSource source) { family.AddMementoSource(source); }); } @@ -109,24 +109,29 @@ XmlNodeList pluginNodes = familyElement.SelectNodes(XmlConstants.PLUGIN_NODE); foreach (XmlElement pluginElement in pluginNodes) { - TypePath pluginPath = TypePath.CreateFromXmlNode(pluginElement); - string concreteKey = pluginElement.GetAttribute(XmlConstants.CONCRETE_KEY_ATTRIBUTE); + attachPlugin(pluginElement, family); + } + } - string context = "creating a Plugin for " + family.PluginType.AssemblyQualifiedName; - _builder.WithType(pluginPath, context, delegate(Type pluggedType) - { - Plugin plugin = new Plugin(pluggedType, concreteKey); - family.Plugins.Add(plugin); + private void attachPlugin(XmlElement pluginElement, PluginFamily family) + { + TypePath pluginPath = TypePath.CreateFromXmlNode(pluginElement); + string concreteKey = pluginElement.GetAttribute(XmlConstants.CONCRETE_KEY_ATTRIBUTE); - foreach ( - XmlElement setterElement in pluginElement.ChildNodes) - { - string setterName = - setterElement.GetAttribute("Name"); - plugin.Setters.Add(setterName); - } - }); - } + string context = "creating a Plugin for " + family.PluginType.AssemblyQualifiedName; + _builder.WithType(pluginPath, context, delegate(Type pluggedType) + { + Plugin plugin = new Plugin(pluggedType, concreteKey); + family.AddPlugin(plugin); + + foreach ( + XmlElement setterElement in pluginElement.ChildNodes) + { + string setterName = + setterElement.GetAttribute("Name"); + plugin.Setters.Add(setterName); + } + }); } // TODO: 3.5 lambda cleanup @@ -138,13 +143,13 @@ return; } - string context = "Creating an InstanceInterceptor for " + - TypePath.GetAssemblyQualifiedName(family.PluginType); + string contextBase = "creating an InstanceInterceptor for " + + TypePath.GetAssemblyQualifiedName(family.PluginType) + "\n"; foreach (XmlNode interceptorNode in interceptorChainNode.ChildNodes) { XmlAttributeInstanceMemento interceptorMemento = new XmlAttributeInstanceMemento(interceptorNode); - + string context = contextBase + interceptorNode.OuterXml; _builder.WithSystemObject<IBuildInterceptor>(interceptorMemento, context, delegate(IBuildInterceptor interceptor) { family.AddInterceptor(interceptor); }); } Modified: trunk/Source/StructureMap/Configuration/GraphBuilder.cs =================================================================== --- trunk/Source/StructureMap/Configuration/GraphBuilder.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Configuration/GraphBuilder.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -82,7 +82,7 @@ } catch (Exception ex) { - _pluginGraph.Log.RegisterError(103, ex, pluginTypePath.ClassName, pluginTypePath.AssemblyName); + _pluginGraph.Log.RegisterError(103, ex, pluginTypePath.AssemblyQualifiedName); } } @@ -108,6 +108,10 @@ Type type = path.FindType(); action(type); } + catch (StructureMapException ex) + { + _pluginGraph.Log.RegisterError(ex); + } catch (Exception ex) { _pluginGraph.Log.RegisterError(131, ex, path.AssemblyQualifiedName, context); Modified: trunk/Source/StructureMap/Configuration/ProfileBuilder.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ProfileBuilder.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Configuration/ProfileBuilder.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -6,6 +6,18 @@ { public class ProfileBuilder : IProfileBuilder { + private static string _overriden_machine_name; + + public static void OverrideMachineName(string machineName) + { + _overriden_machine_name = machineName; + } + + public static void ResetMachineName() + { + _overriden_machine_name = string.Empty; + } + private readonly string _machineName; private readonly PluginGraph _pluginGraph; private readonly ProfileManager _profileManager; @@ -72,6 +84,11 @@ public static string GetMachineName() { + if (!string.IsNullOrEmpty(_overriden_machine_name)) + { + return _overriden_machine_name; + } + string machineName = string.Empty; try { Modified: trunk/Source/StructureMap/Configuration/StructureMapConfigurationSection.cs =================================================================== --- trunk/Source/StructureMap/Configuration/StructureMapConfigurationSection.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Configuration/StructureMapConfigurationSection.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -26,7 +26,6 @@ IList<XmlNode> nodes = ConfigurationSettings.GetConfig(XmlConstants.STRUCTUREMAP) as IList<XmlNode>; if (nodes == null) { - // TODO -- need to get this into PluginGraph instead throw new StructureMapException(105, XmlConstants.STRUCTUREMAP); } return nodes; Added: trunk/Source/StructureMap/Diagnostics/CharacterWidth.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/CharacterWidth.cs (rev 0) +++ trunk/Source/StructureMap/Diagnostics/CharacterWidth.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -0,0 +1,39 @@ +namespace StructureMap.Diagnostics +{ + internal class CharacterWidth + { + internal static CharacterWidth[] For(int count) + { + CharacterWidth[] widths = new CharacterWidth[count]; + for (int i = 0; i < widths.Length; i++) + { + widths[i] = new CharacterWidth(); + } + + return widths; + } + + private int _width = 0; + + internal void SetWidth(int width) + { + if (width > _width) + { + _width = width; + } + } + + internal void Add(int add) + { + _width += add; + } + + internal int Width + { + get + { + return _width; + } + } + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Diagnostics/DividerLine.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/DividerLine.cs (rev 0) +++ trunk/Source/StructureMap/Diagnostics/DividerLine.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -0,0 +1,27 @@ +using System.IO; + +namespace StructureMap.Diagnostics +{ + internal class DividerLine : Line + { + private readonly char _character; + + internal DividerLine(char character) + { + _character = character; + } + + public void OverwriteCounts(CharacterWidth[] widths) + { + // no-op + } + + public void Write(TextWriter writer, CharacterWidth[] widths) + { + foreach (CharacterWidth width in widths) + { + writer.Write(string.Empty.PadRight(width.Width, _character)); + } + } + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Diagnostics/Line.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/Line.cs (rev 0) +++ trunk/Source/StructureMap/Diagnostics/Line.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -0,0 +1,10 @@ +using System.IO; + +namespace StructureMap.Diagnostics +{ + internal interface Line + { + void OverwriteCounts(CharacterWidth[] widths); + void Write(TextWriter writer, CharacterWidth[] widths); + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Diagnostics/TextLine.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/TextLine.cs (rev 0) +++ trunk/Source/StructureMap/Diagnostics/TextLine.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -0,0 +1,32 @@ +using System.IO; + +namespace StructureMap.Diagnostics +{ + internal class TextLine : Line + { + private readonly string[] _contents; + + internal TextLine(string[] contents) + { + _contents = contents; + } + + public void OverwriteCounts(CharacterWidth[] widths) + { + for (int i = 0; i < widths.Length; i++) + { + CharacterWidth width = widths[i]; + width.SetWidth(_contents[i].Length); + } + } + + public void Write(TextWriter writer, CharacterWidth[] widths) + { + for (int i = 0; i < widths.Length; i++) + { + CharacterWidth width = widths[i]; + writer.Write(_contents[i].PadRight(width.Width)); + } + } + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Diagnostics/TextReportWriter.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/TextReportWriter.cs (rev 0) +++ trunk/Source/StructureMap/Diagnostics/TextReportWriter.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; + +namespace StructureMap.Diagnostics +{ + public class TextReportWriter + { + private readonly int _columnCount; + private List<Line> _lines = new List<Line>(); + + public TextReportWriter(int columnCount) + { + _columnCount = columnCount; + } + + public void AddDivider(char character) + { + _lines.Add(new DividerLine(character)); + } + + public void AddText(params string[] contents) + { + _lines.Add(new TextLine(contents)); + } + + public void Write(StringWriter writer) + { + CharacterWidth[] widths = CharacterWidth.For(_columnCount); + + foreach (Line line in _lines) + { + line.OverwriteCounts(widths); + } + + for (int i = 0; i < widths.Length - 1; i++) + { + CharacterWidth width = widths[i]; + width.Add(5); + } + + foreach (Line line in _lines) + { + writer.WriteLine(); + line.Write(writer, widths); + } + } + + public string Write() + { + StringBuilder sb = new StringBuilder(); + StringWriter writer = new StringWriter(sb); + + Write(writer); + + return sb.ToString(); + } + + public void DumpToConsole() + { + System.Console.WriteLine(Write()); + } + + public void DumpToDebug() + { + Debug.WriteLine(Write()); + } + } +} Modified: trunk/Source/StructureMap/Diagnostics/Tokens.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/Tokens.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Diagnostics/Tokens.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -6,11 +6,13 @@ namespace StructureMap.Diagnostics { + public delegate void Action(); + public class GraphLog { private readonly List<Source> _sources = new List<Source>(); private Source _currentSource; - private List<Error> _errors = new List<Error>(); + private readonly List<Error> _errors = new List<Error>(); public int ErrorCount { @@ -45,6 +47,13 @@ } + + public void RegisterError(StructureMapException ex) + { + Error error = new Error(ex); + addError(error); + } + private void addError(Error error) { error.Source = _currentSource; @@ -68,16 +77,75 @@ public void AssertHasError(int errorCode) { + string message = "No error with code " + errorCode + "\nHad errors: "; foreach (Error error in _errors) { + message += error.Code + ", "; if (error.Code == errorCode) { return; } } - throw new ApplicationException("No error with code " + errorCode); + throw new ApplicationException(message); } + + public void AssertHasNoError(int errorCode) + { + foreach (Error error in _errors) + { + if (error.Code == errorCode) + { + throw new ApplicationException("Has error " + errorCode); + } + } + } + + public TryAction Try(Action action) + { + return new TryAction(action, this); + } + + public class TryAction + { + private readonly Action _action; + private readonly GraphLog _log; + + internal TryAction(Action action, GraphLog log) + { + _action = action; + _log = log; + } + + public void AndReportErrorAs(int code, params object[] args) + { + try + { + _action(); + } + catch (Exception ex) + { + _log.RegisterError(code, ex, args); + } + } + + public void AndLogAnyErrors() + { + try + { + _action(); + } + catch (StructureMapException ex) + { + _log.RegisterError(ex); + } + catch (Exception ex) + { + _log.RegisterError(400, ex); + } + } + } + } public class Source @@ -154,13 +222,11 @@ { private readonly string _description; private readonly string _name; - private PluginType _pluginType; - public InstanceToken(string name, string description, PluginType pluginType) + public InstanceToken(string name, string description) { _name = name; _description = description; - _pluginType = pluginType; } @@ -174,12 +240,6 @@ get { return _description; } } - - public PluginType PluginType - { - get { return _pluginType; } - } - #region IEquatable<InstanceToken> Members public bool Equals(InstanceToken instanceToken) @@ -187,7 +247,6 @@ if (instanceToken == null) return false; if (!Equals(_name, instanceToken._name)) return false; if (!Equals(_description, instanceToken._description)) return false; - if (!Equals(_pluginType, instanceToken._pluginType)) return false; return true; } @@ -208,7 +267,6 @@ { int result = _name != null ? _name.GetHashCode() : 0; result = 29*result + (_description != null ? _description.GetHashCode() : 0); - result = 29*result + (_pluginType != null ? _pluginType.GetHashCode() : 0); return result; } } Added: trunk/Source/StructureMap/Diagnostics/WhatDoIHaveWriter.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/WhatDoIHaveWriter.cs (rev 0) +++ trunk/Source/StructureMap/Diagnostics/WhatDoIHaveWriter.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Text; +using StructureMap.Graph; +using StructureMap.Pipeline; + +namespace StructureMap.Diagnostics +{ + public class WhatDoIHaveWriter : IPipelineGraphVisitor + { + private readonly PipelineGraph _graph; + private TextReportWriter _writer; + private List<Instance> _instances; + + public WhatDoIHaveWriter(PipelineGraph graph) + { + _graph = graph; + + } + + public string GetText() + { + _writer = new TextReportWriter(3); + _instances = new List<Instance>(); + + _writer.AddDivider('='); + _writer.AddText("PluginType", "Name", "Description"); + + _graph.Visit(this); + + _writer.AddDivider('='); + + return _writer.Write(); + } + + void IPipelineGraphVisitor.PluginType(Type pluginType, Instance defaultInstance) + { + _writer.AddDivider('-'); + string[] contents = new string[]{TypePath.GetAssemblyQualifiedName(pluginType), string.Empty, string.Empty}; + + if (defaultInstance != null) + { + setContents(contents, defaultInstance); + + } + + _writer.AddText(contents); + } + + private void setContents(string[] contents, Instance instance) + { + InstanceToken token = instance.CreateToken(); + contents[1] = token.Name; + contents[2] = token.Description; + + _instances.Add(instance); + } + + void IPipelineGraphVisitor.Instance(Type pluginType, Instance instance) + { + if (_instances.Contains(instance)) + { + return; + } + + string[] contents = new string[]{string.Empty, string.Empty, string.Empty}; + setContents(contents, instance); + + _writer.AddText(contents); + } + } +} Modified: trunk/Source/StructureMap/Graph/Constructor.cs =================================================================== --- trunk/Source/StructureMap/Graph/Constructor.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Graph/Constructor.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -107,5 +107,10 @@ if (IsEnum(parameterType)) visitor.EnumParameter(info); if (IsString(parameterType)) visitor.StringParameter(info); } + + public bool HasArguments() + { + return _ctor.GetParameters().Length > 0; + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs =================================================================== --- trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -91,9 +91,8 @@ public static PluginFamily CreateTemplatedClone(PluginFamily baseFamily, params Type[] templateTypes) { Type templatedType = baseFamily.PluginType.MakeGenericType(templateTypes); - PluginFamily templatedFamily = new PluginFamily(templatedType); + PluginFamily templatedFamily = new PluginFamily(templatedType, baseFamily.Parent); templatedFamily.DefaultInstanceKey = baseFamily.DefaultInstanceKey; - templatedFamily.Parent = baseFamily.Parent; templatedFamily.Policy = baseFamily.Policy.Clone(); // Add Plugins Modified: trunk/Source/StructureMap/Graph/PluginCollection.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginCollection.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Graph/PluginCollection.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -78,18 +78,6 @@ #endregion - /// <summary> - /// Adds a new Plugin by the PluggedType - /// </summary> - /// <param name="pluggedType"></param> - /// <param name="concreteKey"></param> - // TODO -- not wild about this method. - [Obsolete("Get rid of this")] - public void Add(Type pluggedType, string concreteKey) - { - Plugin plugin = new Plugin(pluggedType, concreteKey); - Add(plugin); - } public void Add(Plugin plugin) { @@ -108,9 +96,7 @@ // Reject if the PluggedType cannot be upcast to the PluginType if (!TypeRules.CanBeCast(_family.PluginType, plugin.PluggedType)) { - // TODO -- get this logged - throw new StructureMapException(114, plugin.PluggedType.FullName, - _family.PluginType.AssemblyQualifiedName); + throw new StructureMapException(104, plugin.PluggedType, _family.PluginType); } _plugins.Add(plugin.PluggedType, plugin); Modified: trunk/Source/StructureMap/Graph/PluginFamily.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginFamily.cs 2008-05-15 18:15:44 UTC (rev 97) +++ trunk/Source/StructureMap/Graph/PluginFamily.cs 2008-05-17 01:25:16 UTC (rev 98) @@ -25,7 +25,13 @@ private IBuildPolicy _policy; public PluginFamily(Type pluginType) + : this(pluginType, new PluginGraph()) { + } + + public PluginFamily(Type pluginType, PluginGraph parent) + { + _parent = parent; _pluginType = pluginType; _plugins = new PluginCollection(this); @@ -93,10 +99,15 @@ public void AddInstance(Instance instance) { + IDiagnosticInstance diagnosticInstance = instance; + if (!diagnosticInstance.CanBePartOfPluginFamily(this)) + { + _parent.Log.RegisterError(106, instance.CreateToken(), _pluginType); + } + _instances.Add(instance); } - // TODO -- eliminate this. Move to GraphBuilder, and wrap error handling around it // For testing public InstanceMemento GetMemento(string instanceKey) @@ -108,10 +119,13 @@ public void Seal() { _mementoList.ForEach(delegate(InstanceMemento memento) - { - Instance instance = memento.ReadInstance(Parent, _pluginType); - _instances.Add(instance); - }); + { + _parent.Log.Try(delegate() + { + Instance instance = memento.ReadInstance(Parent, _pluginType); + _instances.Add(instance); + }).AndLogAnyErrors(); + }); discoverImplicitInstances(); @@ -166,20 +180,26 @@ { if (!HasPlugin(pluggedType)) { - _plugins.Add(new Plugin(pluggedType)); + AddPlugin(new Plugin(pluggedType)); } } public Plugin AddPlugin(Type pluggedType, string key) { Plugin plugin = new Plugin(pluggedType, key); - _plugins.Add(plugin); +... [truncated message content] |
From: <jer...@us...> - 2008-05-26 17:39:12
|
Revision: 99 http://structuremap.svn.sourceforge.net/structuremap/?rev=99&view=rev Author: jeremydmiller Date: 2008-05-26 10:39:08 -0700 (Mon, 26 May 2008) Log Message: ----------- cleaning up all the Profile FI and generics problems. Little refactoring to simplify the FI development, validation development, the ValidationBuildSession Modified Paths: -------------- trunk/Source/StructureMap/Attributes/ValidationMethodAttribute.cs trunk/Source/StructureMap/BuildSession.cs trunk/Source/StructureMap/Configuration/ConfigurationParser.cs trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs trunk/Source/StructureMap/Configuration/DSL/Registry.cs trunk/Source/StructureMap/Configuration/ProfileBuilder.cs trunk/Source/StructureMap/Diagnostics/WhatDoIHaveWriter.cs trunk/Source/StructureMap/Graph/AssemblyScanner.cs trunk/Source/StructureMap/Graph/PluginFamily.cs trunk/Source/StructureMap/Graph/PluginGraph.cs trunk/Source/StructureMap/Graph/TypePath.cs trunk/Source/StructureMap/InstanceManager.cs trunk/Source/StructureMap/ObjectFactory.cs trunk/Source/StructureMap/Pipeline/ConfiguredInstance.cs trunk/Source/StructureMap/Pipeline/ConstructorInstance.cs trunk/Source/StructureMap/Pipeline/Instance.cs trunk/Source/StructureMap/Pipeline/LiteralInstance.cs trunk/Source/StructureMap/Pipeline/Profile.cs trunk/Source/StructureMap/PipelineGraph.cs trunk/Source/StructureMap/PluginGraphBuilder.cs trunk/Source/StructureMap/StructureMap.csproj trunk/Source/StructureMap/StructureMapConfiguration.cs trunk/Source/StructureMap/StructureMapException.resx trunk/Source/StructureMap.Testing/AlternativeConfigurationTester.cs trunk/Source/StructureMap.Testing/BuildSessionTester.cs trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserBuilderTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/ProfileExpressionTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/RegistryTester.cs trunk/Source/StructureMap.Testing/Configuration/InlineInstanceDefinitionInProfileAndMachineNodesTester.cs trunk/Source/StructureMap.Testing/Configuration/ProfileBuilderTester.cs trunk/Source/StructureMap.Testing/Container/ExceptionHandling/StructureMapExceptionTester.cs trunk/Source/StructureMap.Testing/Container/FullStackFacadeTester.cs trunk/Source/StructureMap.Testing/Container/InstanceFactoryTester.cs trunk/Source/StructureMap.Testing/Container/InstanceManagerTester.cs trunk/Source/StructureMap.Testing/DataAccess/CommandFactoryTester.cs trunk/Source/StructureMap.Testing/DataAccess/ExecutionStates/AutoCommitExecutionStateTester.cs trunk/Source/StructureMap.Testing/DataAccess/ExecutionStates/TransactionalExecutionStateTester.cs trunk/Source/StructureMap.Testing/DataAccess/TemplatedCommandTester.cs trunk/Source/StructureMap.Testing/GenericsAcceptanceTester.cs trunk/Source/StructureMap.Testing/GenericsIntegrationTester.cs trunk/Source/StructureMap.Testing/Graph/PluginFamilyTester.cs trunk/Source/StructureMap.Testing/Graph/PluginGraphTester.cs trunk/Source/StructureMap.Testing/Graph/SetterInjectionTester.cs trunk/Source/StructureMap.Testing/Graph/TypePathTester.cs trunk/Source/StructureMap.Testing/ObjectFactoryTester.cs trunk/Source/StructureMap.Testing/Pipeline/ConfiguredInstanceTester.cs trunk/Source/StructureMap.Testing/StructureMap.Testing.csproj trunk/Source/StructureMap.Testing/StructureMapConfigurationTester.cs trunk/Source/StructureMap.Testing/TestData/DataMother.cs trunk/Source/StructureMap.Testing/TestData/DefaultProfileConfig.xml trunk/Source/StructureMap.Testing/TestData/ObjectMother.config trunk/Source/StructureMap.Testing/TestData/SampleConfig.xml trunk/Source/StructureMap.Testing.GenericWidgets/Widgets.cs trunk/Source/StructureMap.Testing.Widget/IWidget.cs trunk/Source/StructureMap.sln Added Paths: ----------- trunk/Source/HTML/ trunk/Source/HTML/HTML.csproj trunk/Source/StructureMap/Delegates.cs trunk/Source/StructureMap/Diagnostics/BuildError.cs trunk/Source/StructureMap/Diagnostics/Error.cs trunk/Source/StructureMap/Diagnostics/ErrorCollection.cs trunk/Source/StructureMap/Diagnostics/GraphLog.cs trunk/Source/StructureMap/Diagnostics/InstanceToken.cs trunk/Source/StructureMap/Diagnostics/ValidationBuildSession.cs trunk/Source/StructureMap/Exceptions/StructureMapConfigurationException.cs trunk/Source/StructureMap.Testing/Diagnostics/IntegrationTester.cs trunk/Source/StructureMap.Testing/Diagnostics/ValidationBuildSessionTester.cs Removed Paths: ------------- trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs trunk/Source/StructureMap/Configuration/DSL/IExpression.cs trunk/Source/StructureMap/Diagnostics/Tokens.cs Added: trunk/Source/HTML/HTML.csproj =================================================================== --- trunk/Source/HTML/HTML.csproj (rev 0) +++ trunk/Source/HTML/HTML.csproj 2008-05-26 17:39:08 UTC (rev 99) @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>8.0.50727</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}</ProjectGuid> + <OutputType>Exe</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>HTML</RootNamespace> + <AssemblyName>HTML</AssemblyName> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project> \ No newline at end of file Modified: trunk/Source/StructureMap/Attributes/ValidationMethodAttribute.cs =================================================================== --- trunk/Source/StructureMap/Attributes/ValidationMethodAttribute.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/Attributes/ValidationMethodAttribute.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -51,19 +51,5 @@ return returnValue; } - - - /// <summary> - /// Executes the marked validation methods, if any, on an object - /// </summary> - /// <param name="target"></param> - public static void CallValidationMethods(object target) - { - MethodInfo[] methods = GetValidationMethods(target.GetType()); - foreach (MethodInfo method in methods) - { - method.Invoke(target, new object[0]); - } - } } } \ No newline at end of file Modified: trunk/Source/StructureMap/BuildSession.cs =================================================================== --- trunk/Source/StructureMap/BuildSession.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/BuildSession.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -10,7 +10,7 @@ { private readonly InterceptorLibrary _interceptorLibrary; private readonly PipelineGraph _pipelineGraph; - private InstanceCache _cache = new InstanceCache(); + private readonly InstanceCache _cache = new InstanceCache(); public BuildSession(PipelineGraph pipelineGraph, InterceptorLibrary interceptorLibrary) { @@ -24,6 +24,12 @@ } + + protected PipelineGraph pipelineGraph + { + get { return _pipelineGraph; } + } + #region IBuildSession Members public object CreateInstance(Type pluginType, string name) @@ -37,7 +43,7 @@ return CreateInstance(pluginType, instance); } - public object CreateInstance(Type pluginType, Instance instance) + public virtual object CreateInstance(Type pluginType, Instance instance) { object result = _cache.Get(pluginType, instance); Modified: trunk/Source/StructureMap/Configuration/ConfigurationParser.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ConfigurationParser.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/Configuration/ConfigurationParser.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -31,6 +31,8 @@ #endregion + public string Description = string.Empty; + private readonly XmlMementoCreator _mementoCreator; private readonly XmlNode _structureMapNode; private string _filePath = string.Empty; Modified: trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.IO; using System.Xml; @@ -8,12 +7,12 @@ { public class ConfigurationParserBuilder { - private readonly List<XmlNode> _nodes = new List<XmlNode>(); + private readonly GraphLog _log; + private readonly List<ConfigurationParser> _parsers = new List<ConfigurationParser>(); private readonly List<string> _otherFiles = new List<string>(); private bool _ignoreDefaultFile = false; - private readonly GraphLog _log; - private bool _useAndEnforceExistenceOfDefaultFile = false; private bool _pullConfigurationFromAppConfig; + private bool _useAndEnforceExistenceOfDefaultFile = false; public ConfigurationParserBuilder(GraphLog log) @@ -37,10 +36,7 @@ public bool PullConfigurationFromAppConfig { get { return _pullConfigurationFromAppConfig; } - set - { - _pullConfigurationFromAppConfig = value; - } + set { _pullConfigurationFromAppConfig = value; } } // TODO: Clean up with 3.5 @@ -53,53 +49,47 @@ if (shouldUseStructureMapConfigFileAt(pathToStructureMapConfig)) { _log.Try(delegate() - { - ConfigurationParser parser = ConfigurationParser.FromFile(pathToStructureMapConfig); - list.Add(parser); - }).AndReportErrorAs(100, pathToStructureMapConfig); + { + ConfigurationParser parser = ConfigurationParser.FromFile(pathToStructureMapConfig); + list.Add(parser); + }).AndReportErrorAs(100, pathToStructureMapConfig); } foreach (string filename in _otherFiles) { _log.Try(delegate() - { - ConfigurationParser parser = ConfigurationParser.FromFile(filename); - list.Add(parser); - }).AndReportErrorAs(160, filename); + { + ConfigurationParser parser = ConfigurationParser.FromFile(filename); + parser.Description = filename; + list.Add(parser); + }).AndReportErrorAs(160, filename); } if (_pullConfigurationFromAppConfig) { _log.Try(delegate() - { - IList<XmlNode> appConfigNodes = StructureMapConfigurationSection.GetStructureMapConfiguration(); - foreach (XmlNode appConfigNode in appConfigNodes) - { - IncludeNode(appConfigNode); - } - }).AndLogAnyErrors(); - + { + IList<XmlNode> appConfigNodes = StructureMapConfigurationSection.GetStructureMapConfiguration(); + foreach (XmlNode appConfigNode in appConfigNodes) + { + IncludeNode(appConfigNode, string.Empty); + } + }).AndLogAnyErrors(); } - // TODO -- some error handling here, or somewhere else. Need to create ConfigurationParser - // as soon as the node is added to try to determine errors - foreach (XmlNode node in _nodes) - { - ConfigurationParser parser = new ConfigurationParser(node); - list.Add(parser); - } + list.AddRange(_parsers); - foreach (ConfigurationParser parser in list.ToArray()) + foreach (ConfigurationParser parser in list.ToArray()) { parser.ForEachFile(_log, delegate(string filename) + { + _log.Try(delegate() { - _log.Try(delegate() - { - ConfigurationParser childParser = ConfigurationParser.FromFile(filename); - list.Add(childParser); - }).AndReportErrorAs(150, filename); - }); + ConfigurationParser childParser = ConfigurationParser.FromFile(filename); + list.Add(childParser); + }).AndReportErrorAs(150, filename); + }); } @@ -109,8 +99,8 @@ private bool shouldUseStructureMapConfigFileAt(string pathToStructureMapConfig) { return - (_useAndEnforceExistenceOfDefaultFile || - File.Exists(pathToStructureMapConfig)) && !_ignoreDefaultFile; + (_useAndEnforceExistenceOfDefaultFile || + File.Exists(pathToStructureMapConfig)) && !_ignoreDefaultFile; } @@ -119,15 +109,19 @@ _otherFiles.Add(filename); } - public void IncludeNode(XmlNode node) + + public void IncludeNode(XmlNode node, string description) { - _nodes.Add(node); + ConfigurationParser parser = new ConfigurationParser(node); + parser.Description = description; + + _parsers.Add(parser); } public static ConfigurationParser[] GetParsers(XmlNode node, GraphLog log) { ConfigurationParserBuilder builder = new ConfigurationParserBuilder(log); - builder.IncludeNode(node); + builder.IncludeNode(node, string.Empty); builder.IgnoreDefaultFile = true; return builder.GetParsers(); Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -10,31 +10,28 @@ /// <summary> /// Represents the parameters for creating instances of a given Type /// </summary> - public class CreatePluginFamilyExpression<PLUGINTYPE> : IExpression + public class CreatePluginFamilyExpression<PLUGINTYPE> { private readonly List<Action<PluginFamily>> _alterations = new List<Action<PluginFamily>>(); private readonly List<Action<PluginGraph>> _children = new List<Action<PluginGraph>>(); private readonly Type _pluginType; private readonly InstanceScope _scope = InstanceScope.PerRequest; - public CreatePluginFamilyExpression() + public CreatePluginFamilyExpression(Registry registry) { _pluginType = typeof (PLUGINTYPE); - } - #region IExpression Members + registry.addExpression(delegate(PluginGraph graph) + { + PluginFamily family = graph.FindFamily(_pluginType); + family.SetScopeTo(_scope); - void IExpression.Configure(PluginGraph graph) - { - PluginFamily family = graph.FindFamily(_pluginType); - family.SetScopeTo(_scope); - - // TODO: clean up with 3.5 - _children.ForEach(delegate(Action<PluginGraph> action) { action(graph); }); - _alterations.ForEach(delegate(Action<PluginFamily> action) { action(family); }); + // TODO: clean up with 3.5 + _children.ForEach(delegate(Action<PluginGraph> action) { action(graph); }); + _alterations.ForEach(delegate(Action<PluginFamily> action) { action(family); }); + }); } - #endregion // TODO: 3.5, Try alterAndContinue(f => {}); private CreatePluginFamilyExpression<PLUGINTYPE> alterAndContinue(Action<PluginFamily> action) @@ -51,10 +48,10 @@ public CreatePluginFamilyExpression<PLUGINTYPE> TheDefaultIs(Instance instance) { return alterAndContinue(delegate(PluginFamily family) - { - family.AddInstance(instance); - family.DefaultInstanceKey = instance.Name; - }); + { + family.AddInstance(instance); + family.DefaultInstanceKey = instance.Name; + }); } public CreatePluginFamilyExpression<PLUGINTYPE> AddInstance(Instance instance) @@ -76,10 +73,10 @@ ExpressionValidator.ValidatePluggabilityOf(typeof (CONCRETETYPE)).IntoPluginType(_pluginType); return alterAndContinue(delegate(PluginFamily family) - { - Plugin plugin = family.Plugins.FindOrCreate(typeof(CONCRETETYPE), true); - family.DefaultInstanceKey = plugin.ConcreteKey; - }); + { + Plugin plugin = family.Plugins.FindOrCreate(typeof (CONCRETETYPE), true); + family.DefaultInstanceKey = plugin.ConcreteKey; + }); return this; } @@ -111,16 +108,16 @@ { _children.Add( delegate(PluginGraph graph) + { + InterceptionFunction function = delegate(object target) { - InterceptionFunction function = delegate(object target) - { - handler((PLUGINTYPE) target); - return target; - }; + handler((PLUGINTYPE) target); + return target; + }; - PluginTypeInterceptor interceptor = new PluginTypeInterceptor(typeof (PLUGINTYPE), function); - graph.InterceptorLibrary.AddInterceptor(interceptor); - }); + PluginTypeInterceptor interceptor = new PluginTypeInterceptor(typeof (PLUGINTYPE), function); + graph.InterceptorLibrary.AddInterceptor(interceptor); + }); return this; } @@ -129,12 +126,12 @@ { _children.Add( delegate(PluginGraph graph) - { - InterceptionFunction function = delegate(object target) { return handler((PLUGINTYPE) target); }; + { + InterceptionFunction function = delegate(object target) { return handler((PLUGINTYPE) target); }; - PluginTypeInterceptor interceptor = new PluginTypeInterceptor(typeof (PLUGINTYPE), function); - graph.InterceptorLibrary.AddInterceptor(interceptor); - }); + PluginTypeInterceptor interceptor = new PluginTypeInterceptor(typeof (PLUGINTYPE), function); + graph.InterceptorLibrary.AddInterceptor(interceptor); + }); return this; } @@ -146,15 +143,15 @@ public CreatePluginFamilyExpression<PLUGINTYPE> AddConcreteType<CONCRETETYPE>(string instanceName) { - ExpressionValidator.ValidatePluggabilityOf(typeof(CONCRETETYPE)).IntoPluginType(typeof(PLUGINTYPE)); + ExpressionValidator.ValidatePluggabilityOf(typeof (CONCRETETYPE)).IntoPluginType(typeof (PLUGINTYPE)); _alterations.Add( delegate(PluginFamily family) - { - Plugin plugin = new Plugin(typeof (CONCRETETYPE)); - plugin.ConcreteKey = instanceName; - family.Plugins.Add(plugin); - } + { + Plugin plugin = new Plugin(typeof (CONCRETETYPE)); + plugin.ConcreteKey = instanceName; + family.Plugins.Add(plugin); + } ); return this; @@ -175,7 +172,7 @@ public CreatePluginFamilyExpression<PLUGINTYPE> AliasConcreteType<PLUGGEDTYPE>(string concreteKey) { - ExpressionValidator.ValidatePluggabilityOf(typeof(PLUGGEDTYPE)).IntoPluginType(typeof(PLUGINTYPE)); + ExpressionValidator.ValidatePluggabilityOf(typeof (PLUGGEDTYPE)).IntoPluginType(typeof (PLUGINTYPE)); _alterations.Add(delegate(PluginFamily family) { family.AddPlugin(typeof (PLUGGEDTYPE), concreteKey); }); Deleted: trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/InstanceDefaultExpression.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -1,77 +0,0 @@ -using System; -using StructureMap.Graph; -using StructureMap.Pipeline; - -namespace StructureMap.Configuration.DSL.Expressions -{ - /// <summary> - /// Use to express the instance of a PluginType for the containing Profile - /// </summary> - public class InstanceDefaultExpression - { - private readonly ProfileExpression _parent; - private readonly Type _pluginType; - private Instance _instance; - private string _instanceKey = string.Empty; - - public InstanceDefaultExpression(Type pluginType, ProfileExpression parent) - { - _pluginType = pluginType; - _parent = parent; - } - - /// <summary> - /// Use a named, preconfigured instance as the default instance for this profile - /// </summary> - /// <param name="instanceKey"></param> - /// <returns></returns> - public ProfileExpression UseNamedInstance(string instanceKey) - { - _instanceKey = instanceKey; - return _parent; - } - - internal void Configure(string profileName, PluginGraph pluginGraph) - { - // The profile instance is defined inline - if (_instance != null) - { - _instanceKey = Profile.InstanceKeyForProfile(profileName); - _instance.Name = _instanceKey; - pluginGraph.FindFamily(_pluginType).AddInstance(_instance); - } - - // Using a referenced key for the profile - else if (!string.IsNullOrEmpty(_instanceKey)) - { - _instance = new ReferencedInstance(_instanceKey); - } - - // Set the default instance in the Profile - if (_instance != null) - { - pluginGraph.ProfileManager.SetDefault(profileName, _pluginType, _instance); - } - - // Blow up if the Profile expression is not complete. - else - { - throw new StructureMapException(304, TypePath.GetAssemblyQualifiedName(_pluginType)); - } - } - - /// <summary> - /// Define the default instance of the PluginType for the containing Profile - /// </summary> - /// <param name="mementoBuilder"></param> - /// <returns></returns> - public ProfileExpression Use(Instance instance) - { - // TODO -- validate that the instance can be plugged into the PluginType - - _instance = instance; - - return _parent; - } - } -} \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -1,44 +1,152 @@ -using System.Collections.Generic; +using System; using StructureMap.Graph; +using StructureMap.Pipeline; namespace StructureMap.Configuration.DSL.Expressions { /// <summary> /// Expression class to help define a runtime Profile /// </summary> - public class ProfileExpression : IExpression + public class ProfileExpression { - private readonly List<InstanceDefaultExpression> _defaults = new List<InstanceDefaultExpression>(); private readonly string _profileName; + private readonly Registry _registry; - public ProfileExpression(string profileName) + public ProfileExpression(string profileName, Registry registry) { _profileName = profileName; + _registry = registry; } - #region IExpression Members - void IExpression.Configure(PluginGraph graph) + /// <summary> + /// Starts the definition of the default instance for the containing Profile + /// </summary> + /// <typeparam name="T"></typeparam> + /// <returns></returns> + public InstanceDefaultExpression<T> For<T>() { - foreach (InstanceDefaultExpression expression in _defaults) + return new InstanceDefaultExpression<T>(this); + } + + /// <summary> + /// Use statement to define the Profile defaults for a Generic type + /// </summary> + /// <param name="pluginType"></param> + /// <returns></returns> + public GenericDefaultExpression For(Type pluginType) + { + return new GenericDefaultExpression(this, pluginType); + } + + #region Nested type: InstanceDefaultExpression + + public class InstanceDefaultExpression<T> + { + private readonly ProfileExpression _parent; + private readonly string _profileName; + private readonly Registry _registry; + + public InstanceDefaultExpression(ProfileExpression parent) { - expression.Configure(_profileName, graph); + _parent = parent; + _registry = parent._registry; + _profileName = parent._profileName; } + + /// <summary> + /// Use a named, preconfigured instance as the default instance for this profile + /// </summary> + /// <param name="instanceKey"></param> + /// <returns></returns> + public ProfileExpression UseNamedInstance(string instanceKey) + { + _registry.addExpression(delegate(PluginGraph graph) + { + graph.SetDefault(_profileName, typeof(T), new ReferencedInstance(instanceKey)); + }); + + return _parent; + } + + /// <summary> + /// Define the default instance of the PluginType for the containing Profile + /// </summary> + /// <param name="mementoBuilder"></param> + /// <returns></returns> + public ProfileExpression Use(Instance instance) + { + instance.Name = "Default Instance for Profile " + _profileName; + + _registry.addExpression(delegate (PluginGraph graph) + { + graph.SetDefault(_profileName, typeof(T), instance); + }); + + return _parent; + } + + public ProfileExpression Use(Func<T> func) + { + ConstructorInstance instance = new ConstructorInstance(delegate { return func(); }); + return Use(instance); + } + + public ProfileExpression Use(T t) + { + LiteralInstance instance = new LiteralInstance(t); + return Use(instance); + } + + public ProfileExpression UseConcreteType<CONCRETETYPE>() + { + ConfiguredInstance instance = new ConfiguredInstance(typeof(CONCRETETYPE)); + return Use(instance); + } + + public ProfileExpression UsePrototypeOf(T template) + { + PrototypeInstance instance = new PrototypeInstance((ICloneable) template); + return Use(instance); + } } #endregion - /// <summary> - /// Starts the definition of the default instance for the containing Profile - /// </summary> - /// <typeparam name="T"></typeparam> - /// <returns></returns> - public InstanceDefaultExpression For<T>() + public class GenericDefaultExpression { - InstanceDefaultExpression defaultExpression = new InstanceDefaultExpression(typeof (T), this); - _defaults.Add(defaultExpression); + private readonly ProfileExpression _parent; + private readonly Type _pluginType; + private readonly Registry _registry; - return defaultExpression; + internal GenericDefaultExpression(ProfileExpression parent, Type pluginType) + { + _parent = parent; + _registry = parent._registry; + _pluginType = pluginType; + } + + public ProfileExpression UseConcreteType(Type concreteType) + { + ConfiguredInstance instance = new ConfiguredInstance(concreteType); + return Use(instance); + } + + public ProfileExpression Use(Instance instance) + { + _registry.addExpression(delegate(PluginGraph graph) + { + graph.SetDefault(_parent._profileName, _pluginType, instance); + }); + + return _parent; + } + + public ProfileExpression UseNamedInstance(string name) + { + ReferencedInstance instance = new ReferencedInstance(name); + return Use(instance); + } } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -11,7 +11,7 @@ /// Expression that directs StructureMap to scan the named assemblies /// for [PluginFamily] and [Plugin] attributes /// </summary> - public class ScanAssembliesExpression : IExpression + public class ScanAssembliesExpression { private readonly List<Assembly> _assemblies = new List<Assembly>(); private readonly Registry _registry; @@ -19,20 +19,15 @@ public ScanAssembliesExpression(Registry registry) { _registry = registry; - } - - #region IExpression Members - - void IExpression.Configure(PluginGraph graph) - { - foreach (Assembly assembly in _assemblies) + _registry.addExpression(delegate(PluginGraph graph) { - graph.Assemblies.Add(assembly); - } + foreach (Assembly assembly in _assemblies) + { + graph.Assemblies.Add(assembly); + } + }); } - #endregion - public ScanAssembliesExpression IncludeTheCallingAssembly() { Assembly callingAssembly = findTheCallingAssembly(); @@ -74,11 +69,11 @@ public ScanAssembliesExpression AddAllTypesOf<PLUGINTYPE>() { _registry.addExpression(delegate(PluginGraph pluginGraph) - { - PluginFamily family = - pluginGraph.FindFamily(typeof (PLUGINTYPE)); - family.SearchForImplicitPlugins = true; - }); + { + PluginFamily family = + pluginGraph.FindFamily(typeof (PLUGINTYPE)); + family.SearchForImplicitPlugins = true; + }); return this; } Deleted: trunk/Source/StructureMap/Configuration/DSL/IExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/IExpression.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/Configuration/DSL/IExpression.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -1,9 +0,0 @@ -using StructureMap.Graph; - -namespace StructureMap.Configuration.DSL -{ - public interface IExpression - { - void Configure(PluginGraph graph); - } -} \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/DSL/Registry.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -9,7 +9,7 @@ { public class Registry : IDisposable { - private readonly List<IExpression> _expressions = new List<IExpression>(); + private readonly List<Action<PluginGraph>> _actions = new List<Action<PluginGraph>>(); private readonly PluginGraph _graph; public Registry(PluginGraph graph) : this() @@ -40,21 +40,18 @@ // no-op; } - protected internal void addExpression(IExpression expression) + internal void addExpression(Action<PluginGraph> alteration) { - _expressions.Add(expression); + _actions.Add(alteration); } - internal void addExpression(PluginGraphAlteration alteration) - { - _expressions.Add(new BasicExpression(alteration)); - } - internal void ConfigurePluginGraph(PluginGraph graph) { - foreach (IExpression expression in _expressions) + graph.Log.StartSource("Registry: " + TypePath.GetAssemblyQualifiedName(GetType())); + + foreach (Action<PluginGraph> action in _actions) { - expression.Configure(graph); + action(graph); } } @@ -67,10 +64,7 @@ /// <returns></returns> public CreatePluginFamilyExpression<PLUGINTYPE> BuildInstancesOf<PLUGINTYPE>() { - CreatePluginFamilyExpression<PLUGINTYPE> expression = new CreatePluginFamilyExpression<PLUGINTYPE>(); - addExpression(expression); - - return expression; + return new CreatePluginFamilyExpression<PLUGINTYPE>(this); } /// <summary> @@ -83,10 +77,7 @@ /// <returns></returns> public CreatePluginFamilyExpression<PLUGINTYPE> ForRequestedType<PLUGINTYPE>() { - CreatePluginFamilyExpression<PLUGINTYPE> expression = new CreatePluginFamilyExpression<PLUGINTYPE>(); - addExpression(expression); - - return expression; + return new CreatePluginFamilyExpression<PLUGINTYPE>(this); } public IInstanceManager BuildInstanceManager() @@ -113,7 +104,10 @@ ConfiguredInstance instance = new ConfiguredInstance(); addExpression( - delegate(PluginGraph pluginGraph) { pluginGraph.FindFamily(typeof (PLUGINTYPE)).AddInstance(instance); }); + delegate(PluginGraph pluginGraph) + { + pluginGraph.FindFamily(typeof (PLUGINTYPE)).AddInstance(instance); + }); return instance; } @@ -200,8 +194,7 @@ /// <returns></returns> public ProfileExpression CreateProfile(string profileName) { - ProfileExpression expression = new ProfileExpression(profileName); - addExpression(expression); + ProfileExpression expression = new ProfileExpression(profileName, this); return expression; } @@ -254,12 +247,12 @@ delegate(PluginGraph pluginGraph) { pluginGraph.InterceptorLibrary.AddInterceptor(interceptor); }); } - public TypeInterceptorExpression IfTypeMatches(Predicate<Type> match) + public MatchedTypeInterceptor IfTypeMatches(Predicate<Type> match) { - TypeInterceptorExpression expression = new TypeInterceptorExpression(match); - _expressions.Add(expression); + MatchedTypeInterceptor interceptor = new MatchedTypeInterceptor(match); + _actions.Add(delegate(PluginGraph graph) { graph.InterceptorLibrary.AddInterceptor(interceptor); }); - return expression; + return interceptor; } @@ -269,33 +262,32 @@ /// <returns></returns> public ScanAssembliesExpression ScanAssemblies() { - ScanAssembliesExpression expression = new ScanAssembliesExpression(this); - addExpression(expression); + return new ScanAssembliesExpression(this); + } - return expression; + + public void AddInstanceOf(Type pluginType, Instance instance) + { + _actions.Add(delegate(PluginGraph graph) { graph.FindFamily(pluginType).AddInstance(instance); }); } + + public void AddInstanceOf<PLUGINTYPE>(Instance instance) + { + _actions.Add(delegate(PluginGraph graph) { graph.FindFamily(typeof (PLUGINTYPE)).AddInstance(instance); }); + } } - public class TypeInterceptorExpression : IExpression, TypeInterceptor + public class MatchedTypeInterceptor : TypeInterceptor { private readonly Predicate<Type> _match; private InterceptionFunction _interception; - internal TypeInterceptorExpression(Predicate<Type> match) + internal MatchedTypeInterceptor(Predicate<Type> match) { _match = match; } - #region IExpression Members - - void IExpression.Configure(PluginGraph graph) - { - graph.InterceptorLibrary.AddInterceptor(this); - } - - #endregion - #region TypeInterceptor Members public bool MatchesType(Type type) @@ -315,25 +307,4 @@ _interception = interception; } } - - internal delegate void PluginGraphAlteration(PluginGraph pluginGraph); - - internal class BasicExpression : IExpression - { - private readonly PluginGraphAlteration _alteration; - - internal BasicExpression(PluginGraphAlteration alteration) - { - _alteration = alteration; - } - - #region IExpression Members - - public void Configure(PluginGraph graph) - { - _alteration(graph); - } - - #endregion - } } \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/ProfileBuilder.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ProfileBuilder.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/Configuration/ProfileBuilder.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -47,10 +47,12 @@ public void OverrideProfile(TypePath typePath, string instanceKey) { - // TODO: what if the Type cannot be found? - - ReferencedInstance instance = new ReferencedInstance(instanceKey); - _profileManager.SetDefault(_lastProfile, typePath.FindType(), instance); + _pluginGraph.Log.Try(delegate() + { + ReferencedInstance instance = new ReferencedInstance(instanceKey); + _pluginGraph.SetDefault(_lastProfile, typePath.FindType(), instance); + + }).AndReportErrorAs(107, typePath.AssemblyQualifiedName); } public void AddMachine(string machineName, string profileName) Added: trunk/Source/StructureMap/Delegates.cs =================================================================== --- trunk/Source/StructureMap/Delegates.cs (rev 0) +++ trunk/Source/StructureMap/Delegates.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace StructureMap +{ + public delegate void Action(); + public delegate void Action<T>(T t); + public delegate void Action<T, T1>(T t, T1 t1); + public delegate T Func<T>(); + +} Added: trunk/Source/StructureMap/Diagnostics/BuildError.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/BuildError.cs (rev 0) +++ trunk/Source/StructureMap/Diagnostics/BuildError.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using StructureMap.Pipeline; + +namespace StructureMap.Diagnostics +{ + public class BuildDependency : IEquatable<BuildDependency> + { + public Instance Instance; + public Type PluginType; + + + public BuildDependency(Type pluginType, Instance instance) + { + Instance = instance; + PluginType = pluginType; + } + + + public bool Equals(BuildDependency buildDependency) + { + if (buildDependency == null) return false; + return Equals(Instance, buildDependency.Instance) && Equals(PluginType, buildDependency.PluginType); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(this, obj)) return true; + return Equals(obj as BuildDependency); + } + + public override int GetHashCode() + { + return (Instance != null ? Instance.GetHashCode() : 0) + 29*(PluginType != null ? PluginType.GetHashCode() : 0); + } + } + + public class BuildError + { + private readonly Instance _instance; + private readonly Type _pluginType; + private StructureMapException _exception; + private readonly List<BuildDependency> _dependencies = new List<BuildDependency>(); + + public BuildError(Type pluginType, Instance instance) + { + _instance = instance; + _pluginType = pluginType; + } + + public void AddDependency(BuildDependency dependency) + { + if (!_dependencies.Contains(dependency)) + { + _dependencies.Add(dependency); + } + } + + public List<BuildDependency> Dependencies + { + get { return _dependencies; } + } + + public Instance Instance + { + get { return _instance; } + } + + public Type PluginType + { + get { return _pluginType; } + } + + public StructureMapException Exception + { + get { return _exception; } + set { _exception = value; } + } + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Diagnostics/Error.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/Error.cs (rev 0) +++ trunk/Source/StructureMap/Diagnostics/Error.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -0,0 +1,108 @@ +using System; +using System.IO; +using System.Resources; + +namespace StructureMap.Diagnostics +{ + public class Error : IEquatable<Error> + { + private readonly int _code; + private readonly string _message; + private readonly string _stackTrace = string.Empty; + public InstanceToken Instance; + public string Source; + + + private Error(int code, string message) + { + _code = code; + _message = message; + } + + public Error(int errorCode, params object[] args) + { + _code = errorCode; + string template = getMessage(errorCode); + if (template == null) template = string.Empty; + + _message = string.Format(template, args); + } + + public Error(int errorCode, Exception ex, params object[] args) : this(errorCode, args) + { + _message += "\n\n" + ex.ToString(); + _stackTrace = ex.StackTrace; + } + + + public Error(StructureMapException exception) + { + _code = exception.ErrorCode; + _message = exception.Message; + _stackTrace = exception.StackTrace; + } + + + public int Code + { + get { return _code; } + } + + #region IEquatable<Error> Members + + public bool Equals(Error error) + { + if (error == null) return false; + if (_code != error._code) return false; + if (!Equals(_message, error._message)) return false; + if (!Equals(_stackTrace, error._stackTrace)) return false; + if (!Equals(Instance, error.Instance)) return false; + return true; + } + + #endregion + + private static string getMessage(int errorCode) + { + ResourceManager resources = new ResourceManager(typeof (StructureMapException)); + return resources.GetString(errorCode.ToString()); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(this, obj)) return true; + return Equals(obj as Error); + } + + public override int GetHashCode() + { + int result = _code; + result = 29*result + (_message != null ? _message.GetHashCode() : 0); + result = 29*result + (_stackTrace != null ? _stackTrace.GetHashCode() : 0); + result = 29*result + (Instance != null ? Instance.GetHashCode() : 0); + return result; + } + + + public override string ToString() + { + return string.Format("Error {0} -- {1}", _code, _message); + } + + public static Error FromMessage(int code, string message) + { + return new Error(code, message); + } + + public void Write(StringWriter writer) + { + // TODO: hit with an extension method for 3.5 + writer.WriteLine("Error: " + Code); + if (Instance != null) writer.WriteLine(Instance.ToString()); + writer.WriteLine("Source: " + Source); + + if (!string.IsNullOrEmpty(_message)) writer.WriteLine(_message); + if (!string.IsNullOrEmpty(_stackTrace)) writer.WriteLine(_stackTrace); + } + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Diagnostics/ErrorCollection.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/ErrorCollection.cs (rev 0) +++ trunk/Source/StructureMap/Diagnostics/ErrorCollection.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using StructureMap.Pipeline; + +namespace StructureMap.Diagnostics +{ + public class ErrorCollection + { + private readonly Dictionary<Instance, BuildError> _buildErrors = new Dictionary<Instance, BuildError>(); + private readonly List<Instance> _brokenInstances = new List<Instance>(); + + + public void LogError( + Instance instance, + Type pluginType, + StructureMapException ex, + IEnumerable<BuildDependency> dependencies) + { + if (_buildErrors.ContainsKey(instance)) + { + BuildError existingError = _buildErrors[instance]; + addDependenciesToError(instance, dependencies, existingError); + } + + if (_brokenInstances.Contains(instance)) + { + return; + } + + InstanceToken token = ((IDiagnosticInstance)instance).CreateToken(); + BuildError error = new BuildError(pluginType, instance); + error.Exception = ex; + + _buildErrors.Add(instance, error); + + addDependenciesToError(instance, dependencies, error); + } + + private void addDependenciesToError(Instance instance, IEnumerable<BuildDependency> dependencies, BuildError error) + { + foreach (BuildDependency dependency in dependencies) + { + if (_brokenInstances.Contains(instance)) + { + continue; + } + + error.AddDependency(dependency); + _brokenInstances.Add(dependency.Instance); + } + } + + public BuildError[] BuildErrors + { + get + { + BuildError[] errors = new BuildError[_buildErrors.Count]; + _buildErrors.Values.CopyTo(errors, 0); + + return errors; + } + } + + public BuildError Find(Type pluginType, string name) + { + foreach (KeyValuePair<Instance, BuildError> pair in _buildErrors) + { + BuildError error = pair.Value; + if (error.PluginType == pluginType && error.Instance.Name == name) + { + return error; + } + } + + return null; + } + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Diagnostics/GraphLog.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/GraphLog.cs (rev 0) +++ trunk/Source/StructureMap/Diagnostics/GraphLog.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -0,0 +1,176 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using StructureMap.Exceptions; +using StructureMap.Graph; +using StructureMap.Pipeline; + +namespace StructureMap.Diagnostics +{ + public class GraphLog + { + private string _currentSource; + private readonly List<Error> _errors = new List<Error>(); + + public int ErrorCount + { + get { return _errors.Count; } + } + + public void StartSource(string description) + { + _currentSource = description; + } + + public void RegisterError(IDiagnosticInstance instance, int code, params object[] args) + { + Error error = new Error(code, args); + error.Instance = instance.CreateToken(); + addError(error); + } + + public void RegisterError(int code, params object[] args) + { + Error error = new Error(code, args); + addError(error); + } + + public void RegisterError(int code, Exception ex, params object[] args) + { + Error error = new Error(code, ex, args); + addError(error); + } + + + + public void RegisterError(StructureMapException ex) + { + Error error = new Error(ex); + addError(error); + } + + private void addError(Error error) + { + error.Source = _currentSource; + _errors.Add(error); + } + + public void AssertFailures() + { + if (_errors.Count == 0) + { + return; + } + + string message = WriteFailures(); + + throw new StructureMapConfigurationException(message); + } + + private string WriteFailures() + { + StringBuilder sb = new StringBuilder(); + StringWriter writer = new StringWriter(sb); + + writer.WriteLine("StructureMap configuration failures:"); + + foreach (Error error in _errors) + { + error.Write(writer); + writer.WriteLine("-----------------------------------------------------------------------------------------------------"); + writer.WriteLine(); + writer.WriteLine(); + } + + return sb.ToString(); + } + + public void AssertHasError(int errorCode, string message) + { + Error error = Error.FromMessage(errorCode, message); + if (!_errors.Contains(error)) + { + string msg = "Did not have the requested Error. Had:\n\n"; + foreach (Error err in _errors) + { + msg += err.ToString() + "\n"; + } + + throw new ApplicationException(msg); + } + } + + public void AssertHasError(int errorCode) + { + string message = "No error with code " + errorCode + "\nHad errors: "; + foreach (Error error in _errors) + { + message += error.Code + ", "; + if (error.Code == errorCode) + { + return; + } + } + + throw new ApplicationException(message); + } + + public void AssertHasNoError(int errorCode) + { + foreach (Error error in _errors) + { + if (error.Code == errorCode) + { + throw new ApplicationException("Has error " + errorCode); + } + } + } + + public TryAction Try(Action action) + { + return new TryAction(action, this); + } + + public class TryAction + { + private readonly Action _action; + private readonly GraphLog _log; + + internal TryAction(Action action, GraphLog log) + { + _action = action; + _log = log; + } + + public void AndReportErrorAs(int code, params object[] args) + { + try + { + _action(); + } + catch (Exception ex) + { + _log.RegisterError(code, ex, args); + } + } + + public void AndLogAnyErrors() + { + try + { + _action(); + } + catch (StructureMapException ex) + { + _log.RegisterError(ex); + } + catch (Exception ex) + { + _log.RegisterError(400, ex); + } + } + } + + } +} \ No newline at end of file Added: trunk/Source/StructureMap/Diagnostics/InstanceToken.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/InstanceToken.cs (rev 0) +++ trunk/Source/StructureMap/Diagnostics/InstanceToken.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -0,0 +1,57 @@ +using System; + +namespace StructureMap.Diagnostics +{ + public class InstanceToken : IEquatable<InstanceToken> + { + private readonly string _description; + private readonly string _name; + + public InstanceToken(string name, string description) + { + _name = name; + _description = description; + } + + + public string Name + { + get { return _name; } + } + + public string Description + { + get { return _description; } + } + + #region IEquatable<InstanceToken> Members + + public bool Equals(InstanceToken instanceToken) + { + if (instanceToken == null) return false; + if (!Equals(_name, instanceToken._name)) return false; + if (!Equals(_description, instanceToken._description)) return false; + return true; + } + + #endregion + + public override string ToString() + { + return string.Format("Instance '{0}' ({1})", _name, _description); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(this, obj)) return true; + return Equals(obj as InstanceToken); + } + + public override int GetHashCode() + { + int result = _name != null ? _name.GetHashCode() : 0; + result = 29*result + (_description != null ? _description.GetHashCode() : 0); + return result; + } + } +} \ No newline at end of file Deleted: trunk/Source/StructureMap/Diagnostics/Tokens.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/Tokens.cs 2008-05-17 01:25:16 UTC (rev 98) +++ trunk/Source/StructureMap/Diagnostics/Tokens.cs 2008-05-26 17:39:08 UTC (rev 99) @@ -1,368 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Resources; -using StructureMap.Graph; -using StructureMap.Pipeline; - -namespace StructureMap.Diagnostics -{ - public delegate void Action(); - - public class GraphLog - { - private readonly List<Source> _sources = new List<Source>(); - private Source _currentSource; - private readonly List<Error> _errors = new List<Error>(); - - pu... [truncated message content] |
From: <jer...@us...> - 2008-05-27 13:25:34
|
Revision: 100 http://structuremap.svn.sourceforge.net/structuremap/?rev=100&view=rev Author: jeremydmiller Date: 2008-05-27 06:25:28 -0700 (Tue, 27 May 2008) Log Message: ----------- Explicit argument passing cleanup, returning an array of all possibles when not totally defined Modified Paths: -------------- trunk/Source/HTML/HTML.csproj trunk/Source/StructureMap/BuildSession.cs trunk/Source/StructureMap/Graph/Constructor.cs trunk/Source/StructureMap/Graph/PluginFamily.cs trunk/Source/StructureMap/Graph/SetterProperty.cs trunk/Source/StructureMap/Graph/TypeRules.cs trunk/Source/StructureMap/IInstanceManager.cs trunk/Source/StructureMap/InstanceManager.cs trunk/Source/StructureMap/ObjectFactory.cs trunk/Source/StructureMap/Pipeline/ConfiguredInstance.cs trunk/Source/StructureMap/Pipeline/ExplicitArguments.cs trunk/Source/StructureMap/StructureMap.csproj trunk/Source/StructureMap.Testing/BuildSessionTester.cs trunk/Source/StructureMap.Testing/Container/ExplicitArgumentTester.cs trunk/Source/StructureMap.Testing/Graph/PluginTester.cs trunk/Source/StructureMap.Testing/StructureMapConfigurationTester.cs Added Paths: ----------- trunk/Source/HTML/ExplicitArguments.htm trunk/Source/StructureMap/ExplicitArgsExpression.cs Property Changed: ---------------- trunk/Source/HTML/ Property changes on: trunk/Source/HTML ___________________________________________________________________ Name: svn:ignore + bin obj Added: trunk/Source/HTML/ExplicitArguments.htm =================================================================== --- trunk/Source/HTML/ExplicitArguments.htm (rev 0) +++ trunk/Source/HTML/ExplicitArguments.htm 2008-05-27 13:25:28 UTC (rev 100) @@ -0,0 +1,19 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> +<html> + <head> + <title></title> + </head> + <body> + <h1> + Explicit Arguments</h1> + <p> + A new feature in StructureMap 2.5 is the ability to pass in arguments to ObjectFactory.</p> + <p> + </p> + <h4> + Primitive Value</h4> + <p> + </p> + + </body> +</html> \ No newline at end of file Modified: trunk/Source/HTML/HTML.csproj =================================================================== --- trunk/Source/HTML/HTML.csproj 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/HTML/HTML.csproj 2008-05-27 13:25:28 UTC (rev 100) @@ -36,4 +36,7 @@ <Target Name="AfterBuild"> </Target> --> + <ItemGroup> + <Content Include="ExplicitArguments.htm" /> + </ItemGroup> </Project> \ No newline at end of file Modified: trunk/Source/StructureMap/BuildSession.cs =================================================================== --- trunk/Source/StructureMap/BuildSession.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap/BuildSession.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; using StructureMap.Graph; using StructureMap.Interceptors; @@ -58,20 +59,28 @@ public Array CreateInstanceArray(Type pluginType, Instance[] instances) { - // TODO -- default to returning all + Array array; + if (instances == null) { - throw new StructureMapException(205, pluginType, "UNKNOWN"); + IList list = forType(pluginType).GetAllInstances(this); + array = Array.CreateInstance(pluginType, list.Count); + for (int i = 0; i < list.Count; i++) + { + array.SetValue(list[i], i); + } } - - // TODO: 3.5, move this to an extension method of Array? - Array array = Array.CreateInstance(pluginType, instances.Length); - for (int i = 0; i < instances.Length; i++) + else { - Instance instance = instances[i]; + // TODO: 3.5, move this to an extension method of Array? + array = Array.CreateInstance(pluginType, instances.Length); + for (int i = 0; i < instances.Length; i++) + { + Instance instance = instances[i]; - object arrayValue = forType(pluginType).Build(this, instance); - array.SetValue(arrayValue, i); + object arrayValue = forType(pluginType).Build(this, instance); + array.SetValue(arrayValue, i); + } } return array; Added: trunk/Source/StructureMap/ExplicitArgsExpression.cs =================================================================== --- trunk/Source/StructureMap/ExplicitArgsExpression.cs (rev 0) +++ trunk/Source/StructureMap/ExplicitArgsExpression.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -0,0 +1,49 @@ +using StructureMap.Pipeline; + +namespace StructureMap +{ + public interface IExplicitProperty + { + ExplicitArgsExpression EqualTo(object value); + } + + public class ExplicitArgsExpression : IExplicitProperty + { + private readonly ExplicitArguments _args = new ExplicitArguments(); + private readonly IInstanceManager _manager; + private string _lastArgName; + + internal ExplicitArgsExpression(IInstanceManager manager) + { + _manager = manager; + } + + #region IExplicitProperty Members + + ExplicitArgsExpression IExplicitProperty.EqualTo(object value) + { + _args.SetArg(_lastArgName, value); + return this; + } + + #endregion + + public ExplicitArgsExpression With<T>(T arg) + { + _args.Set<T>(arg); + return this; + } + + public IExplicitProperty With(string argName) + { + _lastArgName = argName; + return this; + } + + + public T GetInstance<T>() + { + return _manager.CreateInstance<T>(_args); + } + } +} \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/Constructor.cs =================================================================== --- trunk/Source/StructureMap/Graph/Constructor.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap/Graph/Constructor.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -66,7 +66,7 @@ { foreach (ParameterInfo parameter in _ctor.GetParameters()) { - if (!IsChild(parameter.ParameterType)) + if (!IsAutoFillable(parameter.ParameterType)) { return false; } Modified: trunk/Source/StructureMap/Graph/PluginFamily.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginFamily.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap/Graph/PluginFamily.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -140,7 +140,8 @@ _parent.Log.Try(delegate() { diagnosticInstance.Preprocess(this); - }).AndReportErrorAs(104, diagnosticInstance.CreateToken(), _pluginType); + }) + .AndReportErrorAs(104, diagnosticInstance.CreateToken(), _pluginType); if (!diagnosticInstance.CanBePartOfPluginFamily(this)) Modified: trunk/Source/StructureMap/Graph/SetterProperty.cs =================================================================== --- trunk/Source/StructureMap/Graph/SetterProperty.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap/Graph/SetterProperty.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -27,7 +27,7 @@ public bool CanBeAutoFilled { - get { return IsChild(_property.PropertyType); } + get { return IsAutoFillable(_property.PropertyType); } } public void Visit(IArgumentVisitor visitor) Modified: trunk/Source/StructureMap/Graph/TypeRules.cs =================================================================== --- trunk/Source/StructureMap/Graph/TypeRules.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap/Graph/TypeRules.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -89,5 +89,11 @@ { return !type.IsInterface && !type.IsAbstract; } + + + protected bool IsAutoFillable(Type type) + { + return IsChild(type) || IsChildArray(type); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/IInstanceManager.cs =================================================================== --- trunk/Source/StructureMap/IInstanceManager.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap/IInstanceManager.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -75,6 +75,8 @@ object CreateInstance(Type pluginType, string instanceKey); PLUGINTYPE CreateInstance<PLUGINTYPE>(ExplicitArguments args); - + + ExplicitArgsExpression With<T>(T arg); + IExplicitProperty With(string argName); } } \ No newline at end of file Modified: trunk/Source/StructureMap/InstanceManager.cs =================================================================== --- trunk/Source/StructureMap/InstanceManager.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap/InstanceManager.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -248,6 +248,16 @@ return writer.GetText(); } + public ExplicitArgsExpression With<T>(T arg) + { + return new ExplicitArgsExpression(this).With<T>(arg); + } + + public IExplicitProperty With(string argName) + { + return new ExplicitArgsExpression(this).With(argName); + } + #endregion private IBuildSession withNewSession() @@ -260,5 +270,7 @@ { return _pipelineGraph.ForType(type); } + + } } \ No newline at end of file Modified: trunk/Source/StructureMap/ObjectFactory.cs =================================================================== --- trunk/Source/StructureMap/ObjectFactory.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap/ObjectFactory.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -238,7 +238,6 @@ #endregion - #region GetInstance /// <summary> /// Returns the default instance of the requested System.Type @@ -347,67 +346,16 @@ public static ExplicitArgsExpression With<T>(T arg) { - return new ExplicitArgsExpression(manager).With<T>(arg); + return manager.With(arg); } public static IExplicitProperty With(string argName) { - return new ExplicitArgsExpression(manager).With(argName); + return manager.With(argName); } - #region Nested type: ExplicitArgsExpression - public class ExplicitArgsExpression : IExplicitProperty - { - private readonly ExplicitArguments _args = new ExplicitArguments(); - private readonly IInstanceManager _manager; - private string _lastArgName; + } - internal ExplicitArgsExpression(IInstanceManager manager) - { - _manager = manager; - } - #region IExplicitProperty Members - - ExplicitArgsExpression IExplicitProperty.EqualTo(object value) - { - _args.SetArg(_lastArgName, value); - return this; - } - - #endregion - - public ExplicitArgsExpression With<T>(T arg) - { - _args.Set<T>(arg); - return this; - } - - public IExplicitProperty With(string argName) - { - _lastArgName = argName; - return this; - } - - - public T GetInstance<T>() - { - return _manager.CreateInstance<T>(_args); - } - } - - #endregion - - #region Nested type: IExplicitProperty - - public interface IExplicitProperty - { - ExplicitArgsExpression EqualTo(object value); - } - - #endregion - - #endregion - } } \ No newline at end of file Modified: trunk/Source/StructureMap/Pipeline/ConfiguredInstance.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/ConfiguredInstance.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap/Pipeline/ConfiguredInstance.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -62,8 +62,12 @@ Instance[] IConfiguredInstance.GetChildrenArray(string propertyName) { - // TODO: Validate and throw exception if missing - return _arrays[propertyName]; + if (_arrays.ContainsKey(propertyName)) + { + return _arrays[propertyName]; + } + + return null; } string IConfiguredInstance.GetProperty(string propertyName) Modified: trunk/Source/StructureMap/Pipeline/ExplicitArguments.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/ExplicitArguments.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap/Pipeline/ExplicitArguments.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -5,9 +5,18 @@ { public class ExplicitArguments { - private readonly Dictionary<string, string> _args = new Dictionary<string, string>(); + private readonly Dictionary<string, object> _args; private readonly Dictionary<Type, object> _children = new Dictionary<Type, object>(); + public ExplicitArguments(Dictionary<string, object> args) + { + _args = args; + } + + public ExplicitArguments() : this(new Dictionary<string, object>()) + { + } + public T Get<T>() where T : class { return (T) Get(typeof (T)); @@ -25,19 +34,19 @@ public void SetArg(string key, object argValue) { - _args.Add(key, argValue.ToString()); + _args.Add(key, argValue); } - public string GetArg(string key) + public object GetArg(string key) { return _args.ContainsKey(key) ? _args[key] : null; } public void Configure(ConfiguredInstance instance) { - foreach (KeyValuePair<string, string> arg in _args) + foreach (KeyValuePair<string, object> arg in _args) { - instance.SetProperty(arg.Key, arg.Value); + instance.SetProperty(arg.Key, arg.Value.ToString()); instance.SetChild(arg.Key, new LiteralInstance(arg.Value)); } } Modified: trunk/Source/StructureMap/StructureMap.csproj =================================================================== --- trunk/Source/StructureMap/StructureMap.csproj 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap/StructureMap.csproj 2008-05-27 13:25:28 UTC (rev 100) @@ -131,6 +131,7 @@ <Compile Include="Diagnostics\WhatDoIHaveWriter.cs" /> <Compile Include="Emitting\ArgumentEmitter.cs" /> <Compile Include="Exceptions\StructureMapConfigurationException.cs" /> + <Compile Include="ExplicitArgsExpression.cs" /> <Compile Include="Graph\Constructor.cs" /> <Compile Include="Graph\IArgumentVisitor.cs" /> <Compile Include="Graph\IPluginFamily.cs" /> Modified: trunk/Source/StructureMap.Testing/BuildSessionTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/BuildSessionTester.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap.Testing/BuildSessionTester.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -134,5 +134,34 @@ Assert.AreNotSame(result1, result3); Assert.AreSame(result3, result4); } + + [Test] + public void If_no_child_array_is_explicitly_defined_return_all_instances() + { + Registry registry = new Registry(); + registry.AddInstanceOf<IWidget>(new ColorWidget("Red")); + registry.AddInstanceOf<IWidget>(new ColorWidget("Blue")); + registry.AddInstanceOf<IWidget>(new ColorWidget("Green")); + + IInstanceManager manager = registry.BuildInstanceManager(); + + WidgetHolder holder = manager.CreateInstance<WidgetHolder>(); + Assert.AreEqual(3, holder.Widgets.Length); + } + + public class WidgetHolder + { + private readonly IWidget[] _widgets; + + public WidgetHolder(IWidget[] widgets) + { + _widgets = widgets; + } + + public IWidget[] Widgets + { + get { return _widgets; } + } + } } } \ No newline at end of file Modified: trunk/Source/StructureMap.Testing/Container/ExplicitArgumentTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Container/ExplicitArgumentTester.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap.Testing/Container/ExplicitArgumentTester.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -1,3 +1,4 @@ +using System.Collections.Generic; using NUnit.Framework; using StructureMap.Configuration.DSL; using StructureMap.Graph; @@ -2,2 +3,3 @@ using StructureMap.Pipeline; +using StructureMap.Testing.Pipeline; @@ -26,38 +28,7 @@ #endregion - public void GetTypedArgumentsFromAnExplicitArgumentsMementoIfThereIsAnExplicitArgument() - { - Assert.Fail("Redo"); - //PluginGraph pluginGraph = new PluginGraph(); - //using (Registry registry = new Registry(pluginGraph)) - //{ - // registry.ForRequestedType<ExplicitTarget>().TheDefaultIs( - // Registry.Instance<ExplicitTarget>() - // .UsingConcreteType<ExplicitTarget>() - // .Child<IProvider>().IsConcreteType<RedProvider>() - // .WithProperty("name").EqualTo("Jeremy") - // ); - //} - - //InstanceMemento inner = pluginGraph.PluginFamilies[typeof (ExplicitTarget)].Source.GetAllMementos()[0]; - //ExplicitArguments args = new ExplicitArguments(); - //ExplicitArgumentMemento memento = new ExplicitArgumentMemento(args, inner); - - //InstanceManager manager = new InstanceManager(pluginGraph); - - //// Get the ExplicitTarget without setting an explicit arg for IProvider - //ExplicitTarget firstTarget = manager.CreateInstance<ExplicitTarget>(memento); - //Assert.IsInstanceOfType(typeof (RedProvider), firstTarget.Provider); - - //// Now, set the explicit arg for IProvider - //args.Set<IProvider>(new BlueProvider()); - //ExplicitTarget secondTarget = manager.CreateInstance<ExplicitTarget>(memento); - //Assert.IsInstanceOfType(typeof (BlueProvider), secondTarget.Provider); - } - - public interface IExplicitTarget { } @@ -234,8 +205,62 @@ Assert.AreEqual("Jeremy", args.GetArg("name")); args.SetArg("age", 34); - Assert.AreEqual("34", args.GetArg("age")); + Assert.AreEqual(34, args.GetArg("age")); } + + [Test] + public void Fill_in_argument_by_name() + { + InstanceManager manager = new InstanceManager(); + manager.AddDefaultInstance<IView, View>(); + + Node theNode = new Node(); + Trade theTrade = new Trade(); + + Command command = manager + .With("node").EqualTo(theNode) + .With<Trade>(theTrade) + .GetInstance<Command>(); + + Assert.IsInstanceOfType(typeof(View), command.View); + Assert.AreSame(theNode, command.Node); + Assert.AreSame(theTrade, command.Trade); + } + + [Test] + public void Pass_in_arguments_as_dictionary() + { + InstanceManager manager = new InstanceManager(); + manager.AddDefaultInstance<IView, View>(); + + Node theNode = new Node(); + Trade theTrade = new Trade(); + + ExplicitArguments args = new ExplicitArguments(); + args.Set<Node>(theNode); + args.SetArg("trade", theTrade); + + Command command = manager.CreateInstance<Command>(args); + + Assert.IsInstanceOfType(typeof(View), command.View); + Assert.AreSame(theNode, command.Node); + Assert.AreSame(theTrade, command.Trade); + } + + [Test] + public void ExplicitArguments_can_return_child_by_name() + { + ExplicitArguments args = new ExplicitArguments(); + Node theNode = new Node(); + args.SetArg("node", theNode); + + IConfiguredInstance instance = new ExplicitInstance<Command>(args, null); + + Assert.AreSame(theNode, instance.GetChild("node", typeof(Node), new StubBuildSession())); + } + + + } public class Lump @@ -257,4 +282,42 @@ get { return _lump; } } } + + + public class Trade{} + public class Node{} + public interface IView{} + public class View : IView {} + + public class Command + { + private readonly Trade _trade; + private readonly Node _node; + private readonly IView _view; + + public Command(Trade trade, Node node, IView view) + { + _trade = trade; + _node = node; + _view = view; + } + + public Trade Trade + { + get { return _trade; } + } + + public Node Node + { + get { return _node; } + } + + public IView View + { + get { return _view; } + } + } + + + } \ No newline at end of file Modified: trunk/Source/StructureMap.Testing/Graph/PluginTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Graph/PluginTester.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap.Testing/Graph/PluginTester.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -76,6 +76,41 @@ } [Test] + public void CanBeAutoFilled_with_child_array_in_ctor() + { + Constructor ctor = new Constructor(typeof(CanBeAutoFilledWithArray)); + Assert.IsTrue(ctor.CanBeAutoFilled()); + } + + public class CanBeAutoFilledWithArray + { + public CanBeAutoFilledWithArray(IWidget[] widgets) + { + + } + + [SetterProperty] + public IWidget[] More + { + get + { + return null; + } + set + { + + } + } + } + + [Test] + public void CanBeAutoFilled_with_child_array_in_setter() + { + SetterPropertyCollection setters = new SetterPropertyCollection(new Plugin(typeof(CanBeAutoFilledWithArray))); + Assert.IsTrue(setters.CanBeAutoFilled()); + } + + [Test] public void CanBeAutoFilledIsTrue() { Plugin plugin = new Plugin(typeof (Mustang)); Modified: trunk/Source/StructureMap.Testing/StructureMapConfigurationTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/StructureMapConfigurationTester.cs 2008-05-26 17:39:08 UTC (rev 99) +++ trunk/Source/StructureMap.Testing/StructureMapConfigurationTester.cs 2008-05-27 13:25:28 UTC (rev 100) @@ -5,6 +5,7 @@ using StructureMap.Configuration; using StructureMap.Graph; using StructureMap.Testing.GenericWidgets; +using StructureMap.Testing.TestData; namespace StructureMap.Testing { @@ -16,6 +17,7 @@ [SetUp] public void SetUp() { + DataMother.RestoreStructureMapConfig(); ObjectFactory.ReInitialize(); StructureMapConfiguration.ResetAll(); } @@ -36,6 +38,37 @@ } [Test] + public void StructureMap_functions_without_StructureMapconfig_file_in_the_default_mode() + { + StructureMapConfiguration.ResetAll(); + DataMother.RemoveStructureMapConfig(); + + PluginGraph graph = StructureMapConfiguration.GetPluginGraph(); + + } + + [Test] + public void Ignore_the_StructureMap_config_file_even_if_it_exists() + { + StructureMapConfiguration.ResetAll(); + StructureMapConfiguration.IgnoreStructureMapConfig = true; + + PluginGraph graph = StructureMapConfiguration.GetPluginGraph(); + + Assert.AreEqual(0, graph.FamilyCount); + } + + [Test] + public void Use_the_StructureMap_config_file_if_it_exists() + { + StructureMapConfiguration.ResetAll(); + DataMother.RestoreStructureMapConfig(); + + PluginGraph graph = StructureMapConfiguration.GetPluginGraph(); + Assert.IsTrue(graph.FamilyCount > 0); + } + + [Test] public void BuildPluginGraph() { PluginGraph graph = StructureMapConfiguration.GetPluginGraph(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jer...@us...> - 2008-05-31 19:47:33
|
Revision: 112 http://structuremap.svn.sourceforge.net/structuremap/?rev=112&view=rev Author: jeremydmiller Date: 2008-05-31 12:47:30 -0700 (Sat, 31 May 2008) Log Message: ----------- The dynamic addition of assemblies at runtime Modified Paths: -------------- trunk/Source/CommonAssemblyInfo.cs trunk/Source/StructureMap/Container.cs trunk/Source/StructureMap/Emitting/BuildInstanceMethod.cs trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs trunk/Source/StructureMap/Graph/PluginCollection.cs trunk/Source/StructureMap/Graph/PluginFamily.cs trunk/Source/StructureMap/IContainer.cs trunk/Source/StructureMap/IInstanceFactory.cs trunk/Source/StructureMap/InstanceFactory.cs trunk/Source/StructureMap/Interceptors/InterceptorLibrary.cs trunk/Source/StructureMap/ObjectFactory.cs trunk/Source/StructureMap/PipelineGraph.cs trunk/Source/StructureMap/StructureMap.csproj trunk/Source/StructureMap.Testing/Attributes/PluginFamilyAttributeTester.cs trunk/Source/StructureMap.Testing/AutoMocking/RhinoAutoMockerTester.cs trunk/Source/StructureMap.Testing/BuildSessionTester.cs trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserBuilderTester.cs trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/AddInstanceTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/AddTypesTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/ConstructorExpressionTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/CreatePluginFamilyTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/CreateProfileTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/DeepInstanceTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/GenericFamilyExpressionTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/InjectArrayTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/InstanceExpressionTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/InterceptAllInstancesOfPluginTypeTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/InterceptorTesting.cs trunk/Source/StructureMap.Testing/Configuration/DSL/ProfileExpressionTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/RegistryIntegratedTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/RegistryTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/ScanAssembliesTester.cs trunk/Source/StructureMap.Testing/Configuration/DefaultInstanceNodeTester.cs trunk/Source/StructureMap.Testing/Configuration/FamilyParserTester.cs trunk/Source/StructureMap.Testing/Configuration/InlineInstanceDefinitionInProfileAndMachineNodesTester.cs trunk/Source/StructureMap.Testing/Configuration/NormalGraphBuilderTester.cs trunk/Source/StructureMap.Testing/Configuration/ProfileBuilderTester.cs trunk/Source/StructureMap.Testing/Configuration/ShortcuttedInstanceNodeTester.cs trunk/Source/StructureMap.Testing/DataAccess/Commands/StoredProcedureCommandTester.cs trunk/Source/StructureMap.Testing/DataAccess/DataSessionTester.cs trunk/Source/StructureMap.Testing/DataAccess/DataSetMapping/ReaderToColumnMapTester.cs trunk/Source/StructureMap.Testing/DataAccess/DataSetMapping/ReaderToTableMapperTester.cs trunk/Source/StructureMap.Testing/DataAccess/Debugging.cs trunk/Source/StructureMap.Testing/DataAccess/StubbedCommand.cs trunk/Source/StructureMap.Testing/DataAccess/StubbedReaderSource.cs trunk/Source/StructureMap.Testing/DataAccess/TemplatedCommandTester.cs trunk/Source/StructureMap.Testing/DataAccess/Tools/TableDataReaderTester.cs trunk/Source/StructureMap.Testing/Diagnostics/IntegrationTester.cs trunk/Source/StructureMap.Testing/Diagnostics/TextReportWriterSmokeTester.cs trunk/Source/StructureMap.Testing/Diagnostics/ValidationBuildSessionTester.cs trunk/Source/StructureMap.Testing/GenericsAcceptanceTester.cs trunk/Source/StructureMap.Testing/GenericsIntegrationTester.cs trunk/Source/StructureMap.Testing/Graph/GenericsPluginGraphTester.cs trunk/Source/StructureMap.Testing/Graph/ParameterInfoCollection.cs trunk/Source/StructureMap.Testing/Graph/PluginFamilyTester.cs trunk/Source/StructureMap.Testing/Graph/PluginGraphTester.cs trunk/Source/StructureMap.Testing/Graph/PluginTester.cs trunk/Source/StructureMap.Testing/Graph/SetterInjectionTester.cs trunk/Source/StructureMap.Testing/Graph/TypePathTester.cs trunk/Source/StructureMap.Testing/ImplicitPluginFromPluggedTypeAttributeTester.cs trunk/Source/StructureMap.Testing/InstanceBuilderListTester.cs trunk/Source/StructureMap.Testing/InstanceMementoInstanceCreationTester.cs trunk/Source/StructureMap.Testing/MementoTester.cs trunk/Source/StructureMap.Testing/MergingTester.cs trunk/Source/StructureMap.Testing/ObjectFactoryTester.cs trunk/Source/StructureMap.Testing/ObjectMother.cs trunk/Source/StructureMap.Testing/Pipeline/BuildStrategiesTester.cs trunk/Source/StructureMap.Testing/Pipeline/ConstructorInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/DefaultInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/InstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/LiteralInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/ProfileManagerMergeTester.cs trunk/Source/StructureMap.Testing/Pipeline/ProfileManagerTester.cs trunk/Source/StructureMap.Testing/Pipeline/ProfileTester.cs trunk/Source/StructureMap.Testing/Pipeline/PrototypeInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/ReferencedInstanceTester.cs trunk/Source/StructureMap.Testing/Pipeline/StubBuildSession.cs trunk/Source/StructureMap.Testing/Pipeline/ThreadLocalStoragePolicyTester.cs trunk/Source/StructureMap.Testing/Pipeline/TypeRulesTester.cs trunk/Source/StructureMap.Testing/PipelineGraphTester.cs trunk/Source/StructureMap.Testing/StructureMap.Testing.csproj trunk/Source/StructureMap.Testing/StructureMapConfigCreator.cs trunk/Source/StructureMap.Testing/StructureMapConfigurationTester.cs trunk/Source/StructureMap.Testing/TestData/DataMother.cs trunk/Source/StructureMap.Testing/TestUtility.cs trunk/Source/StructureMap.Testing/XmlWriting/ElementChecker.cs Added Paths: ----------- trunk/Source/StructureMap/Util/ trunk/Source/StructureMap/Util/Cache.cs trunk/Source/StructureMap.Testing/Graph/ArrayConstructorTester.cs trunk/Source/StructureMap.Testing/Graph/ContainerConstructorAttributeTester.cs trunk/Source/StructureMap.Testing/Graph/ContainerTester.cs trunk/Source/StructureMap.Testing/Graph/DynamicInjectionTester.cs trunk/Source/StructureMap.Testing/Graph/EmittingTester.cs trunk/Source/StructureMap.Testing/Graph/EnumerationTester.cs trunk/Source/StructureMap.Testing/Graph/ExplicitArgumentTester.cs trunk/Source/StructureMap.Testing/Graph/FillDependenciesTester.cs trunk/Source/StructureMap.Testing/Graph/FullStackFacadeTester.cs trunk/Source/StructureMap.Testing/Graph/ImplicitDefaultTest.cs trunk/Source/StructureMap.Testing/Graph/InstanceFactoryTester.cs trunk/Source/StructureMap.Testing/Graph/IntegratedTester.cs trunk/Source/StructureMap.Testing/Graph/PluggableAttributeTester.cs trunk/Source/StructureMap.Testing/Graph/PluginFamilyMergeTester.cs trunk/Source/StructureMap.Testing/Graph/PluginGraphBuilderTester.cs trunk/Source/StructureMap.Testing/Graph/SetterInjectionEmittingTester.cs trunk/Source/StructureMap.Testing/Graph/TypeFindingTester.cs Removed Paths: ------------- trunk/Source/StructureMap.Testing/Container/ Modified: trunk/Source/CommonAssemblyInfo.cs =================================================================== --- trunk/Source/CommonAssemblyInfo.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/CommonAssemblyInfo.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -1,4 +1,3 @@ -using System; using System.Reflection; using System.Runtime.InteropServices; @@ -12,11 +11,10 @@ // </auto-generated> //------------------------------------------------------------------------------ -[assembly: ComVisibleAttribute(false)] -[assembly: AssemblyVersionAttribute("2.5.0.0000")] -[assembly: AssemblyCopyrightAttribute("Copyright (c) 2007, Jeremy D. Miller")] -[assembly: AssemblyProductAttribute("StructureMap")] -[assembly: AssemblyCompanyAttribute("")] -[assembly: AssemblyConfigurationAttribute("release")] -[assembly: AssemblyInformationalVersionAttribute("2.5.0.0000")] - +[assembly : ComVisible(false)] +[assembly : AssemblyVersion("2.5.0.0000")] +[assembly : AssemblyCopyright("Copyright (c) 2007, Jeremy D. Miller")] +[assembly : AssemblyProduct("StructureMap")] +[assembly : AssemblyCompany("")] +[assembly : AssemblyConfiguration("release")] +[assembly : AssemblyInformationalVersion("2.5.0.0000")] \ No newline at end of file Modified: trunk/Source/StructureMap/Container.cs =================================================================== --- trunk/Source/StructureMap/Container.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/Container.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -90,22 +90,6 @@ _pipelineGraph.Inject(instance); } - public void InjectByName<PLUGINTYPE>(PLUGINTYPE instance, string instanceKey) - { - LiteralInstance literalInstance = new LiteralInstance(instance); - literalInstance.Name = instanceKey; - - AddInstance<PLUGINTYPE>(literalInstance); - } - - public void InjectByName<PLUGINTYPE, CONCRETETYPE>(string instanceKey) - { - ConfiguredInstance instance = new ConfiguredInstance(typeof(CONCRETETYPE)); - instance.Name = instanceKey; - - AddInstance<PLUGINTYPE>(instance); - } - public T GetInstance<T>() { return (T) GetInstance(typeof (T)); @@ -118,9 +102,14 @@ public void InjectStub<T>(T instance) { - InjectStub(typeof (T), instance); + Inject<T>(instance); } + public void InjectStub<T>(string name, T instance) + { + throw new NotImplementedException(); + } + public IList<T> GetAllInstances<T>() { List<T> list = new List<T>(); @@ -180,7 +169,7 @@ /// </summary> /// <param name="pluginType"></param> /// <param name="instance"></param> - public void SetDefault(Type pluginType, Instance instance) + public void Inject(Type pluginType, Instance instance) { _pipelineGraph.SetDefault(pluginType, instance); } @@ -196,7 +185,22 @@ _pipelineGraph.SetDefault(pluginType, reference); } + public void SetDefault(Type pluginType, Instance instance) + { + _pipelineGraph.SetDefault(pluginType, instance); + } + public void SetDefault<T>(Instance instance) + { + SetDefault(typeof(T), instance); + } + + public void SetDefault<PLUGINTYPE, CONCRETETYPE>() where CONCRETETYPE : PLUGINTYPE + { + SetDefault<PLUGINTYPE>(new ConfiguredInstance(typeof(CONCRETETYPE))); + } + + /// <summary> /// Attempts to create a new instance of the requested type. Automatically inserts the default /// configured instance for each dependency in the StructureMap constructor function. @@ -243,19 +247,20 @@ return forType(type).GetAllInstances(withNewSession()); } - public void AddInstance<T>(Instance instance) + public void Configure(Action<Registry> configure) { - _pipelineGraph.AddInstance<T>(instance); - } + lock (this) + { + Registry registry = new Registry(); + configure(registry); - public void AddInstance<PLUGINTYPE, CONCRETETYPE>() where CONCRETETYPE : PLUGINTYPE - { - _pipelineGraph.AddInstance<PLUGINTYPE, CONCRETETYPE>(); - } + PluginGraph graph = registry.Build(); - public void AddDefaultInstance<PLUGINTYPE, CONCRETETYPE>() - { - _pipelineGraph.AddDefaultInstance<PLUGINTYPE, CONCRETETYPE>(); + graph.Log.AssertFailures(); + + _interceptorLibrary.ImportFrom(graph.InterceptorLibrary); + _pipelineGraph.ImportFrom(graph); + } } public string WhatDoIHave() Modified: trunk/Source/StructureMap/Emitting/BuildInstanceMethod.cs =================================================================== --- trunk/Source/StructureMap/Emitting/BuildInstanceMethod.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/Emitting/BuildInstanceMethod.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -12,19 +12,9 @@ public class BuildInstanceMethod : Method { private readonly Plugin _plugin; - //private readonly ConstructorInfo _constructor; - //private readonly ParameterEmitter _parameterEmitter; public BuildInstanceMethod(Plugin plugin) : base() { - //_constructor = plugin.GetConstructor(); - - //_parameterEmitter = new StringParameterEmitter(); - - //_parameterEmitter.AttachNextSibling(new PrimitiveParameterEmitter()); - //_parameterEmitter.AttachNextSibling(new EnumParameterEmitter()); - //_parameterEmitter.AttachNextSibling(new ChildParameterEmitter()); - //_parameterEmitter.AttachNextSibling(new ChildArrayParameterEmitter()); _plugin = plugin; } Modified: trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs =================================================================== --- trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -1,18 +1,27 @@ using System; using System.Collections.Generic; using StructureMap.Pipeline; +using StructureMap.Util; namespace StructureMap.Graph { public class GenericsPluginGraph { - private readonly Dictionary<Type, PluginFamily> _families; + private readonly Cache<Type, PluginFamily> _families; public GenericsPluginGraph() { - _families = new Dictionary<Type, PluginFamily>(); + _families = new Cache<Type, PluginFamily>(delegate(Type pluginType) + { + return new PluginFamily(pluginType); + }); } + public int FamilyCount + { + get { return _families.Count; } + } + public static bool CanBeCast(Type pluginType, Type pluggedType) { try @@ -64,7 +73,7 @@ public void AddFamily(PluginFamily family) { - _families.Add(family.PluginType, family); + _families.Store(family.PluginType, family); } @@ -72,9 +81,9 @@ { Type basicType = templatedType.GetGenericTypeDefinition(); - if (_families.ContainsKey(basicType)) + if (_families.Has(basicType)) { - PluginFamily basicFamily = _families[basicType]; + PluginFamily basicFamily = _families.Retrieve(basicType); Type[] templatedParameterTypes = templatedType.GetGenericArguments(); profileManager.CopyDefaults(basicType, templatedType); @@ -106,13 +115,14 @@ } // TODO -- Got a big problem here. Intances need to be copied over - foreach (IDiagnosticInstance instance in baseFamily.GetAllInstances()) + baseFamily.EachInstance(delegate(Instance i) { + IDiagnosticInstance instance = i; if (instance.CanBePartOfPluginFamily(templatedFamily)) { - templatedFamily.AddInstance((Instance) instance); + templatedFamily.AddInstance((Instance)instance); } - } + }); // Need to attach the new PluginFamily to the old PluginGraph baseFamily.Parent.PluginFamilies.Add(templatedFamily); @@ -169,5 +179,24 @@ } return isValid; } + + public void ImportFrom(GenericsPluginGraph source) + { + foreach (PluginFamily sourceFamily in source._families) + { + ImportFrom(sourceFamily); + } + } + + public void ImportFrom(PluginFamily sourceFamily) + { + PluginFamily destinationFamily = FindFamily(sourceFamily.PluginType); + destinationFamily.ImportFrom(sourceFamily); + } + + public PluginFamily FindFamily(Type pluginType) + { + return _families.Retrieve(pluginType); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/PluginCollection.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginCollection.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/Graph/PluginCollection.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using StructureMap.Util; namespace StructureMap.Graph { @@ -10,7 +11,7 @@ public class PluginCollection : IEnumerable<Plugin> { private readonly PluginFamily _family; - private readonly Dictionary<Type, Plugin> _plugins = new Dictionary<Type, Plugin>(); + private readonly Cache<Type, Plugin> _plugins = new Cache<Type, Plugin>(); public PluginCollection(PluginFamily family) { @@ -21,10 +22,7 @@ { get { - Plugin[] returnValue = new Plugin[_plugins.Count]; - _plugins.Values.CopyTo(returnValue, 0); - - return returnValue; + return _plugins.GetAll(); } } @@ -34,13 +32,13 @@ } /// <summary> - /// Gets a Plugin by its PluggedType + /// Gets a Plugin by its pluggedType /// </summary> - /// <param name="PluggedType"></param> + /// <param name="pluggedType"></param> /// <returns></returns> - public Plugin this[Type PluggedType] + public Plugin this[Type pluggedType] { - get { return _plugins[PluggedType]; } + get { return _plugins.Retrieve(pluggedType); } } /// <summary> @@ -52,15 +50,10 @@ { get { - foreach (KeyValuePair<Type, Plugin> pair in _plugins) + return _plugins.Find(delegate(Plugin plugin) { - if (pair.Value.ConcreteKey == concreteKey) - { - return pair.Value; - } - } - - return null; + return plugin.ConcreteKey == concreteKey; + }); } } @@ -68,7 +61,7 @@ IEnumerator<Plugin> IEnumerable<Plugin>.GetEnumerator() { - return _plugins.Values.GetEnumerator(); + return _plugins.GetEnumerator(); } public IEnumerator GetEnumerator() @@ -81,7 +74,7 @@ public void Add(Plugin plugin) { - if (_plugins.ContainsKey(plugin.PluggedType)) + if (_plugins.Has(plugin.PluggedType)) { Plugin peer = this[plugin.PluggedType]; peer.MergeSetters(plugin); @@ -99,7 +92,8 @@ throw new StructureMapException(104, plugin.PluggedType, _family.PluginType); } - _plugins.Add(plugin.PluggedType, plugin); + + _plugins.Store(plugin.PluggedType, plugin); } /// <summary> @@ -130,20 +124,25 @@ public List<Plugin> FindAutoFillablePlugins() { List<Plugin> list = new List<Plugin>(); - foreach (Plugin plugin in _plugins.Values) + _plugins.Each(delegate(Plugin plugin) { if (plugin.CanBeAutoFilled) { list.Add(plugin); } - } + }); return list; } public bool HasPlugin(Type pluggedType) { - return _plugins.ContainsKey(pluggedType); + return _plugins.Has(pluggedType); } + + public void Fill(Plugin plugin) + { + _plugins.Fill(plugin.PluggedType, plugin); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/PluginFamily.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginFamily.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/Graph/PluginFamily.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -2,6 +2,7 @@ using System.Collections.Generic; using StructureMap.Attributes; using StructureMap.Pipeline; +using StructureMap.Util; namespace StructureMap.Graph { @@ -14,7 +15,7 @@ { private readonly Predicate<Type> _explicitlyMarkedPluginFilter; private readonly Predicate<Type> _implicitPluginFilter; - private readonly List<Instance> _instances = new List<Instance>(); + private readonly Cache<string, Instance> _instances = new Cache<string, Instance>(delegate { return null; }); private readonly List<InstanceMemento> _mementoList = new List<InstanceMemento>(); private readonly PluginCollection _plugins; private readonly Type _pluginType; @@ -99,7 +100,7 @@ public void AddInstance(Instance instance) { - _instances.Add(instance); + _instances.Store(instance.Name, instance); } @@ -117,7 +118,7 @@ _parent.Log.Try(delegate() { Instance instance = memento.ReadInstance(Parent, _pluginType); - _instances.Add(instance); + AddInstance(instance); }).AndLogAnyErrors(); }); @@ -127,28 +128,28 @@ if (_instances.Count == 1) { - _defaultKey = _instances[0].Name; + _defaultKey = _instances.First.Name; } } private void validatePluggabilityOfInstances() { - foreach (Instance instance in _instances) + _instances.Each(delegate(Instance instance) { IDiagnosticInstance diagnosticInstance = instance; _parent.Log.Try(delegate() { - diagnosticInstance.Preprocess(this); + diagnosticInstance.Preprocess(this); }) .AndReportErrorAs(104, diagnosticInstance.CreateToken(), _pluginType); - + if (!diagnosticInstance.CanBePartOfPluginFamily(this)) { _parent.Log.RegisterError(104, diagnosticInstance.CreateToken(), _pluginType); } - } + }); } private void discoverImplicitInstances() @@ -164,14 +165,14 @@ } } - public Instance[] GetAllInstances() + public void EachInstance(Action<Instance> action) { - return _instances.ToArray(); + _instances.Each(action); } public Instance GetInstance(string name) { - return _instances.Find(delegate(Instance i) { return i.Name == name; }); + return _instances.Retrieve(name); } @@ -192,12 +193,17 @@ return _plugins.HasPlugin(pluggedType); } - public void AddPlugin(Type pluggedType) + public Plugin AddPlugin(Type pluggedType) { if (!HasPlugin(pluggedType)) { - AddPlugin(new Plugin(pluggedType)); + Plugin plugin = new Plugin(pluggedType); + AddPlugin(plugin); + + return plugin; } + + return Plugins[pluggedType]; } public Plugin AddPlugin(Type pluggedType, string key) @@ -270,6 +276,11 @@ set { _defaultKey = value ?? string.Empty; } } + public int InstanceCount + { + get { return _instances.Count; } + } + #endregion public Plugin FindPlugin(Type pluggedType) @@ -313,5 +324,23 @@ profile.FillTypeInto(PluginType, defaultInstance); } + + public void ImportFrom(PluginFamily source) + { + source.EachInstance(delegate(Instance instance) + { + _instances.Fill(instance.Name, instance); + }); + + foreach (Plugin plugin in source.Plugins) + { + Plugins.Fill(plugin); + } + } + + public Instance FirstInstance() + { + return _instances.First; + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/IContainer.cs =================================================================== --- trunk/Source/StructureMap/IContainer.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/IContainer.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using StructureMap.Configuration.DSL; using StructureMap.Pipeline; namespace StructureMap @@ -11,43 +12,30 @@ T GetInstance<T>(); T FillDependencies<T>(); object FillDependencies(Type type); - void InjectStub<T>(T instance); + IList<T> GetAllInstances<T>(); - void SetDefaultsToProfile(string profile); + T GetInstance<T>(Instance instance); - /// <summary> - /// Sets up the Container to return the object in the "stub" argument anytime - /// any instance of the PluginType is requested - /// </summary> - /// <param name="pluginType"></param> - /// <param name="stub"></param> - void InjectStub(Type pluginType, object stub); - IList GetAllInstances(Type type); - void AddInstance<T>(Instance instance); - void AddInstance<PLUGINTYPE, CONCRETETYPE>() where CONCRETETYPE : PLUGINTYPE; - void AddDefaultInstance<PLUGINTYPE, CONCRETETYPE>(); + + void Configure(Action<Registry> configure); void Inject<PLUGINTYPE>(PLUGINTYPE instance); - void InjectByName<PLUGINTYPE>(PLUGINTYPE instance, string instanceKey); - void InjectByName<PLUGINTYPE, CONCRETETYPE>(string instanceKey); + void InjectStub(Type pluginType, object stub); + void InjectStub<T>(T instance); + void InjectStub<T>(string name, T instance); + void SetDefault(Type pluginType, string instanceKey); + void SetDefault(Type pluginType, Instance instance); + void SetDefault<T>(Instance instance); + void SetDefault<PLUGINTYPE, CONCRETETYPE>() where CONCRETETYPE : PLUGINTYPE; + void SetDefaultsToProfile(string profile); + string WhatDoIHave(); - /// <summary> - /// Sets the default instance for the PluginType - /// </summary> - /// <param name="pluginType"></param> - /// <param name="instance"></param> - void SetDefault(Type pluginType, Instance instance); - /// <summary> - /// Sets the default instance for the PluginType - /// </summary> - /// <param name="pluginType"></param> - /// <param name="instanceKey"></param> - void SetDefault(Type pluginType, string instanceKey); + /// <summary> /// Creates a new object instance of the requested type Modified: trunk/Source/StructureMap/IInstanceFactory.cs =================================================================== --- trunk/Source/StructureMap/IInstanceFactory.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/IInstanceFactory.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -1,5 +1,6 @@ using System; using System.Collections; +using StructureMap.Graph; using StructureMap.Pipeline; namespace StructureMap @@ -21,5 +22,6 @@ InstanceBuilder FindBuilderByType(Type pluggedType); InstanceBuilder FindBuilderByConcreteKey(string concreteKey); void ForEachInstance(Action<Instance> action); + void ImportFrom(PluginFamily family); } } \ No newline at end of file Modified: trunk/Source/StructureMap/InstanceFactory.cs =================================================================== --- trunk/Source/StructureMap/InstanceFactory.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/InstanceFactory.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -1,8 +1,8 @@ using System; using System.Collections; -using System.Collections.Generic; using StructureMap.Graph; using StructureMap.Pipeline; +using StructureMap.Util; namespace StructureMap { @@ -12,7 +12,10 @@ public class InstanceFactory : IInstanceFactory { private readonly InstanceBuilderList _instanceBuilders; - private readonly Dictionary<string, Instance> _instances = new Dictionary<string, Instance>(); + + private readonly Cache<string, Instance> _instances = + new Cache<string, Instance>(delegate { return null; }); + private readonly Type _pluginType; private readonly IBuildPolicy _policy = new BuildPolicy(); @@ -20,7 +23,6 @@ public InstanceFactory(Type pluginType) : this(new PluginFamily(pluginType)) { - } /// <summary> @@ -41,10 +43,8 @@ _pluginType = family.PluginType; _instanceBuilders = new InstanceBuilderList(family.PluginType, family.Plugins.All); - foreach (Instance instance in family.GetAllInstances()) - { - AddInstance(instance); - } + + family.EachInstance(delegate(Instance instance) { AddInstance(instance); }); } catch (StructureMapException) { @@ -93,29 +93,21 @@ public void ForEachInstance(Action<Instance> action) { - foreach (KeyValuePair<string, Instance> pair in _instances) - { - action(pair.Value); - } + _instances.Each(action); } public void AddInstance(Instance instance) { - if (_instances.ContainsKey(instance.Name)) - { - _instances[instance.Name] = instance; - } - else - { - _instances.Add(instance.Name, instance); - } + _instances.Store(instance.Name, instance); } - [Obsolete] public Instance AddType<T>() + [Obsolete] + public Instance AddType<T>() { InstanceBuilder builder = _instanceBuilders.FindByType(typeof (T)); - ConfiguredInstance instance = new ConfiguredInstance(typeof(T)).WithName(TypePath.GetAssemblyQualifiedName(typeof(T))); + ConfiguredInstance instance = + new ConfiguredInstance(typeof (T)).WithName(TypePath.GetAssemblyQualifiedName(typeof (T))); AddInstance(instance); @@ -126,11 +118,11 @@ { IList list = new ArrayList(); - foreach (KeyValuePair<string, Instance> pair in _instances) + _instances.Each(delegate(Instance instance) { - object instance = Build(session, pair.Value); - list.Add(instance); - } + object builtObject = Build(session, instance); + list.Add(builtObject); + }); return list; } @@ -142,28 +134,18 @@ public Instance FindInstance(string name) { - if (!_instances.ContainsKey(name)) - { - return null; - } - - return _instances[name]; + return _instances.Retrieve(name); } #endregion - public void Merge(PluginFamily family) + public void ImportFrom(PluginFamily family) { _instanceBuilders.Add(family.Plugins); - foreach (Instance instance in family.GetAllInstances()) + family.EachInstance(delegate(Instance instance) { - if (_instances.ContainsKey(instance.Name)) - { - continue; - } - - AddInstance(instance); - } + _instances.Fill(instance.Name, instance); + }); } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Interceptors/InterceptorLibrary.cs =================================================================== --- trunk/Source/StructureMap/Interceptors/InterceptorLibrary.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/Interceptors/InterceptorLibrary.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -18,6 +18,15 @@ _interceptors.Add(interceptor); } + public void ImportFrom(InterceptorLibrary source) + { + lock (_locker) + { + _analyzedInterceptors.Clear(); + _interceptors.AddRange(source._interceptors); + } + } + public CompoundInterceptor FindInterceptor(Type type) { if (_analyzedInterceptors.ContainsKey(type)) Modified: trunk/Source/StructureMap/ObjectFactory.cs =================================================================== --- trunk/Source/StructureMap/ObjectFactory.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/ObjectFactory.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Security.Permissions; +using StructureMap.Configuration.DSL; using StructureMap.Graph; using StructureMap.Pipeline; @@ -85,50 +86,6 @@ manager.Inject<PLUGINTYPE>(instance); } - /// <summary> - /// Injects a new instance of PLUGINTYPE by name. - /// </summary> - /// <typeparam name="PLUGINTYPE"></typeparam> - /// <param name="instance"></param> - /// <param name="instanceKey"></param> - public static void InjectByName<PLUGINTYPE>(PLUGINTYPE instance, string instanceKey) - { - manager.InjectByName<PLUGINTYPE>(instance, instanceKey); - } - - /// <summary> - /// Injects a new instance of CONCRETETYPE to PLUGINTYPE by name. - /// </summary> - /// <typeparam name="PLUGINTYPE"></typeparam> - /// <typeparam name="CONCRETETYPE"></typeparam> - /// <param name="instanceKey"></param> - public static void InjectByName<PLUGINTYPE, CONCRETETYPE>(string instanceKey) - { - manager.InjectByName<PLUGINTYPE, CONCRETETYPE>(instanceKey); - } - - /// <summary> - /// StructureMap will return an instance of CONCRETETYPE whenever - /// a PLUGINTYPE is requested - /// </summary> - /// <typeparam name="PLUGINTYPE"></typeparam> - /// <typeparam name="CONCRETETYPE"></typeparam> - public static void InjectDefaultType<PLUGINTYPE, CONCRETETYPE>() where CONCRETETYPE : PLUGINTYPE - { - manager.AddDefaultInstance<PLUGINTYPE, CONCRETETYPE>(); - } - - /// <summary> - /// Adds a new CONCRETETYPE to StructureMap so that an instance of CONCRETETYPE - /// will be returned from a call to ObjectFactory.GetAllInstance<PLUGINTYPE>() - /// </summary> - /// <typeparam name="PLUGINTYPE"></typeparam> - /// <typeparam name="CONCRETETYPE"></typeparam> - public static void AddType<PLUGINTYPE, CONCRETETYPE>() where CONCRETETYPE : PLUGINTYPE - { - manager.AddInstance<PLUGINTYPE, CONCRETETYPE>(); - } - #region Container and setting defaults private static IContainer manager @@ -184,12 +141,32 @@ /// Strictly used for testing scenarios /// </summary> /// <param name="manager"></param> - internal static void ReplaceManager(IContainer manager) + internal static void ReplaceManager(IContainer container) { - _manager = manager; + _manager = container; } + public static void Configure(Action<Registry> configure) + { + manager.Configure(configure); + } + public static void SetDefault(Type pluginType, Instance instance) + { + manager.SetDefault(pluginType, instance); + } + + public static void SetDefault<PLUGINTYPE>(Instance instance) + { + manager.SetDefault<PLUGINTYPE>(instance); + } + + public static void SetDefault<PLUGINTYPE, CONCRETETYPE>() where CONCRETETYPE : PLUGINTYPE + { + manager.SetDefault<PLUGINTYPE, CONCRETETYPE>(); + } + + /// <summary> /// Fires when the ObjectFactory is refreshed /// </summary> Modified: trunk/Source/StructureMap/PipelineGraph.cs =================================================================== --- trunk/Source/StructureMap/PipelineGraph.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/PipelineGraph.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -42,6 +42,23 @@ } } + public void ImportFrom(PluginGraph graph) + { + foreach (PluginFamily family in graph.PluginFamilies) + { + if (family.IsGenericTemplate) + { + _genericsGraph.ImportFrom(family); + } + else + { + ForType(family.PluginType).ImportFrom(family); + } + } + + _profileManager.ImportFrom(graph.ProfileManager); + } + public MissingFactoryFunction OnMissingFactory { set { _missingFactory = value; } Modified: trunk/Source/StructureMap/StructureMap.csproj =================================================================== --- trunk/Source/StructureMap/StructureMap.csproj 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap/StructureMap.csproj 2008-05-31 19:47:30 UTC (rev 112) @@ -376,6 +376,7 @@ <Compile Include="ErrorMessages.cs" /> <Compile Include="Pipeline\ConfiguredInstance.Building.cs" /> <Compile Include="Pipeline\IStructuredInstance.cs" /> + <Compile Include="Util\Cache.cs" /> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <PropertyGroup> Added: trunk/Source/StructureMap/Util/Cache.cs =================================================================== --- trunk/Source/StructureMap/Util/Cache.cs (rev 0) +++ trunk/Source/StructureMap/Util/Cache.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -0,0 +1,153 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using StructureMap.Graph; + +namespace StructureMap.Util +{ + public class Cache<KEY, VALUE> : IEnumerable<VALUE> where VALUE : class + { + private readonly Dictionary<KEY, VALUE> _values = new Dictionary<KEY, VALUE>(); + private readonly Func<KEY, VALUE> _onMissing = delegate(KEY key) + { + string message = string.Format("Key '{0}' could not be found", key); + throw new KeyNotFoundException(message); + }; + + private Func<VALUE, KEY> _getKey = delegate { throw new NotImplementedException(); }; + + public Cache() + { + } + + public Cache(Func<KEY, VALUE> onMissing) + { + _onMissing = onMissing; + } + + public Func<VALUE, KEY> GetKey + { + get { return _getKey; } + set { _getKey = value; } + } + + public int Count + { + get + { + return _values.Count; + } + } + + public VALUE First + { + get + { + foreach (KeyValuePair<KEY, VALUE> pair in _values) + { + return pair.Value; + } + + return null; + } + } + + public void Store(KEY key, VALUE value) + { + if (_values.ContainsKey(key)) + { + _values[key] = value; + } + else + { + _values.Add(key, value); + } + } + + public void Fill(KEY key, VALUE value) + { + if (_values.ContainsKey(key)) + { + return; + } + + _values.Add(key, value); + } + + public VALUE Retrieve(KEY key) + { + if (!_values.ContainsKey(key)) + { + VALUE value = _onMissing(key); + _values.Add(key, value); + } + + return _values[key]; + } + + public void Each(Action<VALUE> action) + { + foreach (KeyValuePair<KEY, VALUE> pair in _values) + { + action(pair.Value); + } + } + + public bool Has(KEY key) + { + return _values.ContainsKey(key); + } + + public bool Exists(Predicate<VALUE> predicate) + { + bool returnValue = false; + + Each(delegate(VALUE value) + { + returnValue |= predicate(value); + }); + + return returnValue; + } + + public VALUE Find(Predicate<VALUE> predicate) + { + foreach (KeyValuePair<KEY, VALUE> pair in _values) + { + if (predicate(pair.Value)) + { + return pair.Value; + } + } + + return null; + } + + public VALUE[] GetAll() + { + VALUE[] returnValue = new VALUE[Count]; + _values.Values.CopyTo(returnValue, 0); + + return returnValue; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable<VALUE>) this).GetEnumerator(); + } + + public IEnumerator<VALUE> GetEnumerator() + { + return _values.Values.GetEnumerator(); + } + + public void Remove(KEY key) + { + if (_values.ContainsKey(key)) + { + _values.Remove(key); + } + } + } +} Modified: trunk/Source/StructureMap.Testing/Attributes/PluginFamilyAttributeTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Attributes/PluginFamilyAttributeTester.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap.Testing/Attributes/PluginFamilyAttributeTester.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -4,9 +4,7 @@ using Rhino.Mocks.Constraints; using StructureMap.Attributes; using StructureMap.Graph; -using StructureMap.Interceptors; using StructureMap.Pipeline; -using StructureMap.Source; namespace StructureMap.Testing.Attributes { @@ -18,9 +16,9 @@ PluginFamilyAttribute att = new PluginFamilyAttribute("something"); att.Scope = scope; - PluginFamily family = new PluginFamily(typeof(TypeThatDoesNotHaveCustomMementoSource)); + PluginFamily family = new PluginFamily(typeof (TypeThatDoesNotHaveCustomMementoSource)); att.Configure(family); - + Assert.IsInstanceOfType(interceptorType, family.Policy); } @@ -85,7 +83,7 @@ using (mocks.Record()) { - SetupResult.For(family.PluginType).Return(typeof(TypeThatDoesNotHaveCustomMementoSource)); + SetupResult.For(family.PluginType).Return(typeof (TypeThatDoesNotHaveCustomMementoSource)); family.AddMementoSource(null); LastCall.Repeat.Never(); @@ -97,7 +95,7 @@ } } - + [Test] public void PerRequest_DoesNot_call_SetScopeTo_on_family() { Modified: trunk/Source/StructureMap.Testing/AutoMocking/RhinoAutoMockerTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/AutoMocking/RhinoAutoMockerTester.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap.Testing/AutoMocking/RhinoAutoMockerTester.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -137,7 +137,7 @@ IMockedService3 service3 = _container.GetInstance<IMockedService3>(); ConcreteClass concreteClass = _container.FillDependencies<ConcreteClass>(); - + Assert.AreSame(service, concreteClass.Service); Assert.AreSame(service2, concreteClass.Service2); Assert.AreSame(service3, concreteClass.Service3); Modified: trunk/Source/StructureMap.Testing/BuildSessionTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/BuildSessionTester.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap.Testing/BuildSessionTester.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -33,28 +33,58 @@ } } + public class WidgetHolder + { + private readonly IWidget[] _widgets; + + public WidgetHolder(IWidget[] widgets) + { + _widgets = widgets; + } + + public IWidget[] Widgets + { + get { return _widgets; } + } + } + [Test] - public void Throw_200_When_trying_to_build_an_instance_that_cannot_be_found() + public void Get_a_unique_value_for_each_individual_buildsession() { - PipelineGraph graph = new PipelineGraph(new PluginGraph()); + int count = 0; - assertActionThrowsErrorCode(200, delegate() + BuildSession session = new BuildSession(new PluginGraph()); + BuildSession session2 = new BuildSession(new PluginGraph()); + ConstructorInstance instance = new ConstructorInstance(delegate { - BuildSession session = new BuildSession(graph, null); - session.CreateInstance(typeof (IGateway), "A Name"); + count++; + return new ColorRule("Red"); }); + + object result1 = session.CreateInstance(typeof (ColorRule), instance); + object result2 = session.CreateInstance(typeof (ColorRule), instance); + object result3 = session2.CreateInstance(typeof (ColorRule), instance); + object result4 = session2.CreateInstance(typeof (ColorRule), instance); + + Assert.AreEqual(2, count); + + Assert.AreSame(result1, result2); + Assert.AreNotSame(result1, result3); + Assert.AreSame(result3, result4); } [Test] - public void When_calling_CreateInstance_if_no_default_can_be_found_throw_202() + public void If_no_child_array_is_explicitly_defined_return_all_instances() { - PipelineGraph graph = new PipelineGraph(new PluginGraph()); - - assertActionThrowsErrorCode(202, delegate() + IContainer manager = new Container(delegate(Registry registry) { - BuildSession session = new BuildSession(graph, null); - session.CreateInstance(typeof (IGateway)); + registry.AddInstanceOf<IWidget>(new ColorWidget("Red")); + registry.AddInstanceOf<IWidget>(new ColorWidget("Blue")); + registry.AddInstanceOf<IWidget>(new ColorWidget("Green")); }); + + WidgetHolder holder = manager.GetInstance<WidgetHolder>(); + Assert.AreEqual(3, holder.Widgets.Length); } [Test] @@ -63,7 +93,7 @@ int count = 0; BuildSession session = new BuildSession(new PluginGraph()); - ConstructorInstance instance = new ConstructorInstance(delegate() + ConstructorInstance instance = new ConstructorInstance(delegate { count++; return new ColorRule("Red"); @@ -73,7 +103,7 @@ object result2 = session.CreateInstance(typeof (ColorRule), instance); object result3 = session.CreateInstance(typeof (ColorRule), instance); object result4 = session.CreateInstance(typeof (ColorRule), instance); - + Assert.AreEqual(1, count); Assert.AreSame(result1, result2); @@ -86,7 +116,7 @@ { int count = 0; - ConstructorInstance instance = new ConstructorInstance(delegate() + ConstructorInstance instance = new ConstructorInstance(delegate { count++; return new ColorRule("Red"); @@ -98,10 +128,10 @@ BuildSession session = new BuildSession(graph); - object result1 = session.CreateInstance(typeof(ColorRule)); - object result2 = session.CreateInstance(typeof(ColorRule)); - object result3 = session.CreateInstance(typeof(ColorRule)); - object result4 = session.CreateInstance(typeof(ColorRule)); + object result1 = session.CreateInstance(typeof (ColorRule)); + object result2 = session.CreateInstance(typeof (ColorRule)); + object result3 = session.CreateInstance(typeof (ColorRule)); + object result4 = session.CreateInstance(typeof (ColorRule)); Assert.AreEqual(1, count); @@ -111,57 +141,27 @@ } [Test] - public void Get_a_unique_value_for_each_individual_buildsession() + public void Throw_200_When_trying_to_build_an_instance_that_cannot_be_found() { - int count = 0; + PipelineGraph graph = new PipelineGraph(new PluginGraph()); - BuildSession session = new BuildSession(new PluginGraph()); - BuildSession session2 = new BuildSession(new PluginGraph()); - ConstructorInstance instance = new ConstructorInstance(delegate() + assertActionThrowsErrorCode(200, delegate { - count++; - return new ColorRule("Red"); + BuildSession session = new BuildSession(graph, null); + session.CreateInstance(typeof (IGateway), "A Name"); }); - - object result1 = session.CreateInstance(typeof(ColorRule), instance); - object result2 = session.CreateInstance(typeof(ColorRule), instance); - object result3 = session2.CreateInstance(typeof(ColorRule), instance); - object result4 = session2.CreateInstance(typeof(ColorRule), instance); - - Assert.AreEqual(2, count); - - Assert.AreSame(result1, result2); - Assert.AreNotSame(result1, result3); - Assert.AreSame(result3, result4); } [Test] - public void If_no_child_array_is_explicitly_defined_return_all_instances() + public void When_calling_CreateInstance_if_no_default_can_be_found_throw_202() { - IContainer manager = new StructureMap.Container(delegate(Registry registry) + PipelineGraph graph = new PipelineGraph(new PluginGraph()); + + assertActionThrowsErrorCode(202, delegate { - registry.AddInstanceOf<IWidget>(new ColorWidget("Red")); - registry.AddInstanceOf<IWidget>(new ColorWidget("Blue")); - registry.AddInstanceOf<IWidget>(new ColorWidget("Green")); + BuildSession session = new BuildSession(graph, null); + session.CreateInstance(typeof (IGateway)); }); - - WidgetHolder holder = manager.GetInstance<WidgetHolder>(); - Assert.AreEqual(3, holder.Widgets.Length); } - - public class WidgetHolder - { - private readonly IWidget[] _widgets; - - public WidgetHolder(IWidget[] widgets) - { - _widgets = widgets; - } - - public IWidget[] Widgets - { - get { return _widgets; } - } - } } } \ No newline at end of file Modified: trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserBuilderTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserBuilderTester.cs 2008-05-30 16:36:24 UTC (rev 111) +++ trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserBuilderTester.cs 2008-05-31 19:47:30 UTC (rev 112) @@ -53,13 +53,23 @@ Converter<ConfigurationParser, string> converter = delegate(ConfigurationParser parser) { return parser.Id; }; - string[] actuals = Array.ConvertAll<ConfigurationParser, string>(parsers, converter); + string[] actuals = Array.ConvertAll(parsers, converter); Array.Sort(actuals); Assert.AreEqual(expected, actuals); } [Test] + public void Do_NOT_Log_exception_100_if_StructureMap_config_is_required_and_missing() + { + assertNoErrorIsLogged(100, delegate + { + DataMother.RemoveStructureMapConfig(); + builder.UseAndEnforceExistenceOfDefaultFile = false; + }); + } + + [Test] public void DoNotUseDefaultAndUseADifferentFile() { DataMother.RemoveStructureMapConfig(); @@ -74,124 +84,107 @@ } [Test] - public void Put_the_file_name_onto_ConfigurationParser() + public void GetIncludes() { + DataMother.RemoveStructureMapConfig(); + + DataMother.WriteDocument("Include1.xml"); + DataMother.WriteDocument("Include2.xml"); + DataMother.WriteDocument("Master.xml"); + builder.UseAndEnforceExistenceOfDefaultFile = false; builder.IgnoreDefaultFile = true; + builder.IncludeFile("Master.xml"); + assertParserIdList("Include1", "Include2", "Master"); + } + + [Test] + public void GetMultiples() + { + DataMother.WriteDocument("Include1.xml"); + DataMother.WriteDocument("Include2.xml"); + DataMother.WriteDocument("Master.xml"); + DataMother.WriteDocument("GenericsTesting.xml"); builder.IncludeFile("GenericsTesting.xml"); + builder.UseAndEnforceExistenceOfDefaultFile = true; + builder.IncludeFile("Master.xml"); - ConfigurationParser[] parsers = builder.GetParsers(); - Assert.AreEqual("GenericsTesting.xml", parsers[0].Description); + assertParserIdList("Generics", "Include1", "Include2", "Main", "Master"); } [Test] public void If_adding_a_node_directly_use_stacktrace_to_get_the_node() { - } [Test] - public void Log_exception_100_if_StructureMap_config_is_required_and_missing() + public void Log_error_150_if_a_designated_Include_cannot_be_opened() { - assertErrorIsLogged(100, delegate() - { - DataMother.RemoveStructureMapConfig(); - builder.UseAndEnforceExistenceOfDefaultFile = true; - }); - } + assertErrorIsLogged(150, delegate + { + builder.IncludeFile("Master.xml"); - [Test] - public void Do_NOT_Log_exception_100_if_StructureMap_config_is_required_and_missing() - { - assertNoErrorIsLogged(100, delegate() - { - DataMother.RemoveStructureMapConfig(); - builder.UseAndEnforceExistenceOfDefaultFile = false; - }); + DataMother.WriteDocument("Include1.xml"); + File.Delete("Include2.xml"); + DataMother.WriteDocument("Master.xml"); + + builder.IgnoreDefaultFile = true; + }); } [Test] - public void Log_exception_160_if_additional_file_cannot_be_opened() + public void Log_error_156_if_Include_node_does_not_have_a_File() { - assertErrorIsLogged(160, delegate() - { - builder.IncludeFile("FileThatDoesNotExist.xml"); - }); + DataMother.WriteDocument("MissingInclude.xml", "<StructureMap><Include></Include></StructureMap>"); + assertErrorIsLogged(156, delegate { builder.IncludeFile("MissingInclude.xml"); }); } [Test] - public void Log_exception_160_if_file_is_malformed() + public void Log_exception_100_if_StructureMap_config_is_required_and_missing() { - assertErrorIsLogged(160, delegate() - { - XmlDocument doc = new XmlDocument(); - doc.LoadXml("<a></a>"); - doc.Save("Malformed.xml"); - builder.IncludeFile("Malformed.xml"); - }); + assertErrorIsLogged(100, delegate + { + DataMother.RemoveStructureMapConfig(); + builder.UseAndEnforceExistenceOfDefaultFile = true; + }); } - [Test] - public void Log_error_150_if_a_designated_Include_cannot_be_opened() + public void Log_exception_160_if_additional_file_cannot_be_opened() { - assertErrorIsLogged(150, delegate() - { - builder.IncludeFile("Master.xml"); - - DataMother.WriteDocument("Include1.xml"); - File.Delete("Include2.xml"); - DataMother.WriteDocument("Master.xml"); - - builder.IgnoreDefaultFile = true; - }); + assertErrorIsLogged(160, delegate { builder.IncludeFile("FileThatDoesNotExist.xml"); }); } [Test] - public void Log_error_156_if_Include_node_does_not_have_a_File() + public void Log_exception_160_if_file_is_malformed() { - DataMother.WriteDocument("MissingInclude.xml", "<StructureMap><Include></Include></StructureMap>"); - assertErrorIsLogged(156, delegate() - { - builder.IncludeFile("MissingInclude.xml"); - }); + assertErrorIsLogged(160, delegate + { + XmlDocument doc = new XmlDocument(); + doc.LoadXml("<a></a>"); + doc.Save("Malformed.xml"); + builder.IncludeFile("Malformed.xml"); + }); } [Test] - public void GetIncludes() + public void Put_the_file_name_onto_ConfigurationParser() { - DataMother.RemoveStructureMapConfig(); - - DataMother.WriteDocument("Include1.xml"); - DataMother.WriteDocument("Include2.xml"); - DataMother.WriteDocument("Master.xml"); - builder.... [truncated message content] |
From: <jer...@us...> - 2008-06-02 16:27:39
|
Revision: 116 http://structuremap.svn.sourceforge.net/structuremap/?rev=116&view=rev Author: jeremydmiller Date: 2008-06-02 09:27:28 -0700 (Mon, 02 Jun 2008) Log Message: ----------- explicited a test Modified Paths: -------------- trunk/Source/CommonAssemblyInfo.cs trunk/Source/StructureMap/Pipeline/ReferencedInstance.cs trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserBuilderTester.cs trunk/Source/StructureMap.Testing/Graph/ContainerTester.cs trunk/Source/StructureMap.Testing/Graph/FullStackFacadeTester.cs trunk/Source/StructureMap.sln Modified: trunk/Source/CommonAssemblyInfo.cs =================================================================== --- trunk/Source/CommonAssemblyInfo.cs 2008-06-02 03:02:16 UTC (rev 115) +++ trunk/Source/CommonAssemblyInfo.cs 2008-06-02 16:27:28 UTC (rev 116) @@ -1,3 +1,4 @@ +using System; using System.Reflection; using System.Runtime.InteropServices; @@ -11,10 +12,11 @@ // </auto-generated> //------------------------------------------------------------------------------ -[assembly : ComVisible(false)] -[assembly : AssemblyVersion("2.5.0.0000")] -[assembly : AssemblyCopyright("Copyright (c) 2007, Jeremy D. Miller")] -[assembly : AssemblyProduct("StructureMap")] -[assembly : AssemblyCompany("")] -[assembly : AssemblyConfiguration("release")] -[assembly : AssemblyInformationalVersion("2.5.0.0000")] \ No newline at end of file +[assembly: ComVisibleAttribute(false)] +[assembly: AssemblyVersionAttribute("2.5.0.0000")] +[assembly: AssemblyCopyrightAttribute("Copyright (c) 2007, Jeremy D. Miller")] +[assembly: AssemblyProductAttribute("StructureMap")] +[assembly: AssemblyCompanyAttribute("")] +[assembly: AssemblyConfigurationAttribute("release")] +[assembly: AssemblyInformationalVersionAttribute("2.5.0.0000")] + Modified: trunk/Source/StructureMap/Pipeline/ReferencedInstance.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/ReferencedInstance.cs 2008-06-02 03:02:16 UTC (rev 115) +++ trunk/Source/StructureMap/Pipeline/ReferencedInstance.cs 2008-06-02 16:27:28 UTC (rev 116) @@ -11,7 +11,11 @@ public ReferencedInstance(string referenceKey) { - // TODO: VALIDATION if referenceKey is null or empty + if (string.IsNullOrEmpty(referenceKey)) + { + throw new ArgumentNullException("referenceKey"); + } + _referenceKey = referenceKey; } Modified: trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserBuilderTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserBuilderTester.cs 2008-06-02 03:02:16 UTC (rev 115) +++ trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserBuilderTester.cs 2008-06-02 16:27:28 UTC (rev 116) @@ -115,11 +115,8 @@ assertParserIdList("Generics", "Include1", "Include2", "Main", "Master"); } - [Test] - public void If_adding_a_node_directly_use_stacktrace_to_get_the_node() - { - } + [Test] public void Log_error_150_if_a_designated_Include_cannot_be_opened() { @@ -142,7 +139,7 @@ assertErrorIsLogged(156, delegate { builder.IncludeFile("MissingInclude.xml"); }); } - [Test] + [Test, Explicit] public void Log_exception_100_if_StructureMap_config_is_required_and_missing() { assertErrorIsLogged(100, delegate Modified: trunk/Source/StructureMap.Testing/Graph/ContainerTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Graph/ContainerTester.cs 2008-06-02 03:02:16 UTC (rev 115) +++ trunk/Source/StructureMap.Testing/Graph/ContainerTester.cs 2008-06-02 16:27:28 UTC (rev 116) @@ -240,5 +240,7 @@ Container manager = new Container(new PluginGraph()); manager.GetInstance<IService>(); } + + } } \ No newline at end of file Modified: trunk/Source/StructureMap.Testing/Graph/FullStackFacadeTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Graph/FullStackFacadeTester.cs 2008-06-02 03:02:16 UTC (rev 115) +++ trunk/Source/StructureMap.Testing/Graph/FullStackFacadeTester.cs 2008-06-02 16:27:28 UTC (rev 116) @@ -1,4 +1,5 @@ using NUnit.Framework; +using StructureMap.Configuration.DSL; using StructureMap.Graph; using StructureMap.Testing.TestData; using StructureMap.Testing.Widget; @@ -212,6 +213,36 @@ Assert.AreSame(rule1, rule2); Assert.AreSame(rule1, rule3); } + + [Test] + public void If_there_is_only_one_instance_of_a_type_use_that_as_default() + { + AClass target = new AClass("Me"); + + Container container = new Container(delegate(Registry registry) + { + registry.AddInstanceOf<AClass>(target); + }); + + + Assert.AreSame(target, container.GetInstance<AClass>()); + } + + public class AClass + { + private readonly string _name; + + public AClass(string name) + { + _name = name; + } + + public string Name + { + get { return _name; } + } + } + } Modified: trunk/Source/StructureMap.sln =================================================================== --- trunk/Source/StructureMap.sln 2008-06-02 03:02:16 UTC (rev 115) +++ trunk/Source/StructureMap.sln 2008-06-02 16:27:28 UTC (rev 116) @@ -49,8 +49,6 @@ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StructureMap.AutoMocking", "StructureMap.AutoMocking\StructureMap.AutoMocking.csproj", "{0ED1B206-A1C9-4A52-BA87-3BA416C8725C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HTML", "HTML\HTML.csproj", "{A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Build|.NET = Build|.NET @@ -229,20 +227,6 @@ {0ED1B206-A1C9-4A52-BA87-3BA416C8725C}.Release|Any CPU.Build.0 = Release|Any CPU {0ED1B206-A1C9-4A52-BA87-3BA416C8725C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {0ED1B206-A1C9-4A52-BA87-3BA416C8725C}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Build|.NET.ActiveCfg = Release|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Build|Any CPU.ActiveCfg = Release|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Build|Any CPU.Build.0 = Release|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Build|Mixed Platforms.ActiveCfg = Release|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Build|Mixed Platforms.Build.0 = Release|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Debug|.NET.ActiveCfg = Debug|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Release|.NET.ActiveCfg = Release|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Release|Any CPU.Build.0 = Release|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {A6358895-641F-4CC2-BE8E-C61EBE1DBEB9}.Release|Mixed Platforms.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jer...@us...> - 2008-06-15 01:49:36
|
Revision: 121 http://structuremap.svn.sourceforge.net/structuremap/?rev=121&view=rev Author: jeremydmiller Date: 2008-06-14 18:49:31 -0700 (Sat, 14 Jun 2008) Log Message: ----------- VS2008 cutover Modified Paths: -------------- trunk/Source/CommonAssemblyInfo.cs trunk/Source/StructureMap/BuildSession.cs trunk/Source/StructureMap/Configuration/ConfigurationParser.cs trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/GenericFamilyExpression.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs trunk/Source/StructureMap/Configuration/DSL/Registry.cs trunk/Source/StructureMap/Configuration/DSL/RegistryExpressions.cs trunk/Source/StructureMap/Configuration/FamilyParser.cs trunk/Source/StructureMap/Configuration/ProfileAndMachineParser.cs trunk/Source/StructureMap/Configuration/ProfileBuilder.cs trunk/Source/StructureMap/Configuration/XmlConstants.cs trunk/Source/StructureMap/Diagnostics/BuildError.cs trunk/Source/StructureMap/Diagnostics/Doctor.cs trunk/Source/StructureMap/Diagnostics/ErrorCollection.cs trunk/Source/StructureMap/Diagnostics/ValidationBuildSession.cs trunk/Source/StructureMap/Emitting/InstanceBuilderAssembly.cs trunk/Source/StructureMap/Graph/AssemblyScanner.cs trunk/Source/StructureMap/Graph/GenericsPluginGraph.cs trunk/Source/StructureMap/Graph/ITypeScanner.cs trunk/Source/StructureMap/Graph/PluginCollection.cs trunk/Source/StructureMap/Graph/PluginFamily.cs trunk/Source/StructureMap/InstanceFactory.cs trunk/Source/StructureMap/InstanceMemento.cs trunk/Source/StructureMap/Interceptors/InterceptorLibrary.cs trunk/Source/StructureMap/PipelineGraph.cs trunk/Source/StructureMap/PluginGraphBuilder.cs trunk/Source/StructureMap/Source/XmlMementoCreator.cs trunk/Source/StructureMap/StructureMap.csproj trunk/Source/StructureMap/StructureMapConfiguration.cs trunk/Source/StructureMap/Util/Cache.cs trunk/Source/StructureMap.AutoMocking/StructureMap.AutoMocking.csproj trunk/Source/StructureMap.DataAccess/StructureMap.DataAccess.csproj trunk/Source/StructureMap.DeploymentTasks/StructureMap.DeploymentTasks.csproj trunk/Source/StructureMap.Testing/BuildSessionTester.cs trunk/Source/StructureMap.Testing/Configuration/ConfigurationParserBuilderTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/AddInstanceTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/AddTypesTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/ConstructorExpressionTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/CreatePluginFamilyTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/DeepInstanceTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/GenericFamilyExpressionTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/InjectArrayTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/InterceptAllInstancesOfPluginTypeTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/InterceptorTesting.cs trunk/Source/StructureMap.Testing/Configuration/DSL/ProfileExpressionTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/RegistryIntegratedTester.cs trunk/Source/StructureMap.Testing/Configuration/FamilyParserTester.cs trunk/Source/StructureMap.Testing/Configuration/NormalGraphBuilderTester.cs trunk/Source/StructureMap.Testing/Diagnostics/ValidationBuildSessionTester.cs trunk/Source/StructureMap.Testing/GenericsAcceptanceTester.cs trunk/Source/StructureMap.Testing/Graph/ContainerTester.cs trunk/Source/StructureMap.Testing/Graph/DefaultConventionScanningTester.cs trunk/Source/StructureMap.Testing/Graph/DynamicInjectionTester.cs trunk/Source/StructureMap.Testing/Graph/EnumerationTester.cs trunk/Source/StructureMap.Testing/Graph/ExceptionHandling/StructureMapExceptionTester.cs trunk/Source/StructureMap.Testing/Graph/ExplicitArgumentTester.cs trunk/Source/StructureMap.Testing/Graph/FullStackFacadeTester.cs trunk/Source/StructureMap.Testing/Graph/InstanceFactoryTester.cs trunk/Source/StructureMap.Testing/Graph/Interceptors/TypeInterceptionTester.cs trunk/Source/StructureMap.Testing/Graph/PluginFamilyTester.cs trunk/Source/StructureMap.Testing/Graph/PluginGraphBuilderTester.cs trunk/Source/StructureMap.Testing/Graph/TypeFindingTester.cs trunk/Source/StructureMap.Testing/Pipeline/ProfileTester.cs trunk/Source/StructureMap.Testing/PipelineGraphTester.cs trunk/Source/StructureMap.Testing/StructureMap.Testing.csproj trunk/Source/StructureMap.Testing/TestUtility.cs trunk/Source/StructureMap.Testing.GenericWidgets/StructureMap.Testing.GenericWidgets.csproj trunk/Source/StructureMap.Testing.Widget/StructureMap.Testing.Widget.csproj trunk/Source/StructureMap.Testing.Widget2/StructureMap.Testing.Widget2.csproj trunk/Source/StructureMap.Testing.Widget3/StructureMap.Testing.Widget3.csproj trunk/Source/StructureMap.Testing.Widget4/StructureMap.Testing.Widget4.csproj trunk/Source/StructureMap.Testing.Widget5/StructureMap.Testing.Widget5.csproj trunk/Source/StructureMap.sln Added Paths: ----------- trunk/Source/StructureMap/Configuration/XmlExtensions.cs trunk/Source/StructureMap/Diagnostics/DoctorReport.cs trunk/Source/StructureMap/Diagnostics/DoctorResult.cs trunk/Source/StructureMap/Diagnostics/DoctorRunner.cs trunk/Source/StructureMap/Diagnostics/ValidationError.cs trunk/Source/StructureMap/Pipeline/SerializedInstance.cs trunk/Source/StructureMap.AutoMocking/StructureMap.AutoMocking.csproj.user trunk/Source/StructureMap.Testing/Diagnostics/DoctorTester.cs trunk/Source/StructureMap.Testing/Diagnostics/WriterExtensions.cs trunk/Source/StructureMap.Testing/Pipeline/SerializedInstanceTester.cs trunk/Source/StructureMap.Testing/SpecificationExtensions.cs trunk/Source/StructureMap.lnk trunk/Source/StructureMapDoctor/ trunk/Source/StructureMapDoctor/Program.cs trunk/Source/StructureMapDoctor/Properties/ trunk/Source/StructureMapDoctor/Properties/AssemblyInfo.cs trunk/Source/StructureMapDoctor/StructureMapDoctor.csproj Modified: trunk/Source/CommonAssemblyInfo.cs =================================================================== --- trunk/Source/CommonAssemblyInfo.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/CommonAssemblyInfo.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -5,7 +5,7 @@ //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. -// Runtime Version:2.0.50727.1433 +// Runtime Version:2.0.50727.1434 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. Modified: trunk/Source/StructureMap/BuildSession.cs =================================================================== --- trunk/Source/StructureMap/BuildSession.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/BuildSession.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -72,7 +72,6 @@ } else { - // TODO: 3.5, move this to an extension method of Array? array = Array.CreateInstance(pluginType, instances.Length); for (int i = 0; i < instances.Length; i++) { Modified: trunk/Source/StructureMap/Configuration/ConfigurationParser.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ConfigurationParser.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/ConfigurationParser.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.IO; using System.Xml; using StructureMap.Diagnostics; @@ -8,89 +7,50 @@ namespace StructureMap.Configuration { - public class ConfigurationParser + public class ConfigurationParser : XmlConstants { #region statics public static ConfigurationParser FromFile(string filename) { - XmlDocument document = new XmlDocument(); + var document = new XmlDocument(); document.Load(filename); - XmlNode structureMapNode = document.SelectSingleNode("//" + XmlConstants.STRUCTUREMAP); + XmlNode structureMapNode = document.SelectSingleNode("//" + STRUCTUREMAP); if (structureMapNode == null) { throw new StructureMapException(155, filename); } - ConfigurationParser parser = new ConfigurationParser(structureMapNode); + var parser = new ConfigurationParser(structureMapNode); parser.FilePath = filename; - + return parser; } #endregion - public string Description = string.Empty; - private readonly XmlMementoCreator _mementoCreator; private readonly XmlNode _structureMapNode; private string _filePath = string.Empty; + public string Description = string.Empty; public ConfigurationParser(XmlNode structureMapNode) { _structureMapNode = structureMapNode; - // TODO: 3.5 cleanup with extension method XmlMementoStyle mementoStyle = XmlMementoStyle.NodeNormalized; - - - XmlAttribute att = _structureMapNode.Attributes[XmlConstants.MEMENTO_STYLE]; - if (att != null) + _structureMapNode.ForAttributeValue(MEMENTO_STYLE, style => { - if (att.Value == XmlConstants.ATTRIBUTE_STYLE) - { - mementoStyle = XmlMementoStyle.AttributeNormalized; - } - } + if (style == ATTRIBUTE_STYLE) mementoStyle = XmlMementoStyle.AttributeNormalized; + }); - _mementoCreator = new XmlMementoCreator( mementoStyle, - XmlConstants.TYPE_ATTRIBUTE, - XmlConstants.KEY_ATTRIBUTE); + TYPE_ATTRIBUTE, + KEY_ATTRIBUTE); } - public void ForEachFile(GraphLog log, Action<string> action) - { - // TODO: Clean up with 3.5 - string includePath = getIncludePath(); - XmlNodeList includeNodes = _structureMapNode.SelectNodes(XmlConstants.INCLUDE_NODE); - foreach (XmlElement includeElement in includeNodes) - { - string fileName = includeElement.GetAttribute("File"); - if (string.IsNullOrEmpty(fileName)) - { - log.RegisterError(156, _filePath); - } - else - { - string includedFile = Path.Combine(includePath, fileName); - action(includedFile); - } - } - } - - private string getIncludePath() - { - if (string.IsNullOrEmpty(_filePath)) - { - return string.Empty; - } - - return Path.GetDirectoryName(_filePath); - } - public string Id { get @@ -107,83 +67,53 @@ set { _filePath = value; } } - public void ParseAssemblies(IGraphBuilder builder) + public void ForEachFile(GraphLog log, Action<string> action) { - parseAssemblies(builder); - } - - - public void ParseInstances(IGraphBuilder builder) - { - XmlNodeList familyNodes = findNodes(XmlConstants.PLUGIN_FAMILY_NODE); - foreach (XmlElement familyElement in familyNodes) + string includePath = getIncludePath(); + _structureMapNode.ForTextInChild("Include/@File").Do(fileName => { - TypePath typePath = TypePath.CreateFromXmlNode(familyElement); - - builder.ConfigureFamily(typePath, - delegate(PluginFamily family) { attachInstances(family, familyElement, builder); }); - } + string includedFile = Path.Combine(includePath, fileName); + action(includedFile); + }); } - private void parseAssemblies(IGraphBuilder builder) + private string getIncludePath() { - XmlNodeList assemblyNodes = findNodes(XmlConstants.ASSEMBLY); - foreach (XmlNode assemblyNode in assemblyNodes) + if (string.IsNullOrEmpty(_filePath)) { - string assemblyName = assemblyNode.Attributes[XmlConstants.NAME].Value; - - builder.AddAssembly(assemblyName); + return string.Empty; } - } - private XmlNodeList findNodes(string nodeName) - { - return _structureMapNode.SelectNodes(nodeName); + return Path.GetDirectoryName(_filePath); } - - public void ParseFamilies(IGraphBuilder builder) + public void ParseAssemblies(IGraphBuilder builder) { - FamilyParser familyParser = new FamilyParser(builder, _mementoCreator); - - XmlNodeList familyNodes = findNodes(XmlConstants.PLUGIN_FAMILY_NODE); - foreach (XmlElement familyElement in familyNodes) - { - familyParser.ParseFamily(familyElement); - } - - XmlNodeList defaultNodes = findNodes(XmlConstants.DEFAULT_INSTANCE); - foreach (XmlElement element in defaultNodes) - { - familyParser.ParseDefaultElement(element); - } - - XmlNodeList instanceNodes = findNodes(XmlConstants.ADD_INSTANCE_NODE); - foreach (XmlElement element in instanceNodes) - { - familyParser.ParseInstanceElement(element); - } + _structureMapNode.ForTextInChild("Assembly/@Name").Do(name => builder.AddAssembly(name)); } - private void attachInstances(PluginFamily family, XmlElement familyElement, IGraphBuilder builder) + private XmlExtensions.XmlNodeExpression forEachNode(string xpath) { - foreach (XmlNode instanceNode in familyElement.ChildNodes) - { - if (instanceNode.Name != XmlConstants.INSTANCE_NODE) - { - continue; - } - - InstanceMemento memento = _mementoCreator.CreateMemento(instanceNode); - family.AddInstance(memento); - } + return _structureMapNode.ForEachChild(xpath); } public void ParseProfilesAndMachines(IGraphBuilder builder) { - ProfileAndMachineParser parser = new ProfileAndMachineParser(builder, _structureMapNode, _mementoCreator); + var parser = new ProfileAndMachineParser(builder, _structureMapNode, _mementoCreator); parser.Parse(); } + + public void Parse(IGraphBuilder builder) + { + var familyParser = new FamilyParser(builder, _mementoCreator); + + forEachNode(PLUGIN_FAMILY_NODE).Do(familyParser.ParseFamily); + forEachNode(DEFAULT_INSTANCE).Do(familyParser.ParseDefaultElement); + forEachNode(ADD_INSTANCE_NODE).Do(familyParser.ParseInstanceElement); + + ParseProfilesAndMachines(builder); + } + } } \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/ConfigurationParserBuilder.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -8,11 +8,11 @@ public class ConfigurationParserBuilder { private readonly GraphLog _log; + private readonly List<string> _otherFiles = new List<string>(); private readonly List<ConfigurationParser> _parsers = new List<ConfigurationParser>(); - private readonly List<string> _otherFiles = new List<string>(); - private bool _ignoreDefaultFile = false; + private bool _ignoreDefaultFile; private bool _pullConfigurationFromAppConfig; - private bool _useAndEnforceExistenceOfDefaultFile = false; + private bool _useAndEnforceExistenceOfDefaultFile; public ConfigurationParserBuilder(GraphLog log) @@ -39,35 +39,39 @@ set { _pullConfigurationFromAppConfig = value; } } - // TODO: Clean up with 3.5 public ConfigurationParser[] GetParsers() { - List<ConfigurationParser> list = new List<ConfigurationParser>(); + var list = new List<ConfigurationParser>(); - // Pick up the configuration in the default StructureMap.config - string pathToStructureMapConfig = StructureMapConfiguration.GetStructureMapConfigurationPath(); - if (shouldUseStructureMapConfigFileAt(pathToStructureMapConfig)) - { - _log.Try(delegate() - { - ConfigurationParser parser = ConfigurationParser.FromFile(pathToStructureMapConfig); - list.Add(parser); - }).AndReportErrorAs(100, pathToStructureMapConfig); - } + addConfigurationFromStructureMapConfig(list); + addConfigurationFromExplicitlyAddedFiles(list); + addConfigurationFromApplicationConfigFile(); - foreach (string filename in _otherFiles) + list.AddRange(_parsers); + + addConfigurationFromIncludeNodes(list); + + return list.ToArray(); + } + + private void addConfigurationFromIncludeNodes(List<ConfigurationParser> list) + { + foreach (ConfigurationParser parser in list.ToArray()) { - _log.Try(delegate() - { - ConfigurationParser parser = ConfigurationParser.FromFile(filename); - parser.Description = filename; - list.Add(parser); - }).AndReportErrorAs(160, filename); + parser.ForEachFile(_log, + filename => _log.Try(() => + { + ConfigurationParser childParser = ConfigurationParser.FromFile(filename); + list.Add(childParser); + }).AndReportErrorAs(150, filename)); } + } + private void addConfigurationFromApplicationConfigFile() + { if (_pullConfigurationFromAppConfig) { - _log.Try(delegate() + _log.Try(() => { IList<XmlNode> appConfigNodes = StructureMapConfigurationSection.GetStructureMapConfiguration(); foreach (XmlNode appConfigNode in appConfigNodes) @@ -76,24 +80,33 @@ } }).AndLogAnyErrors(); } + } - list.AddRange(_parsers); + private void addConfigurationFromExplicitlyAddedFiles(List<ConfigurationParser> list) + { + foreach (string filename in _otherFiles) + { + _log.Try(() => + { + ConfigurationParser parser = ConfigurationParser.FromFile(filename); + parser.Description = filename; + list.Add(parser); + }).AndReportErrorAs(160, filename); + } + } - foreach (ConfigurationParser parser in list.ToArray()) + private void addConfigurationFromStructureMapConfig(List<ConfigurationParser> list) + { +// Pick up the configuration in the default StructureMap.config + string pathToStructureMapConfig = StructureMapConfiguration.GetStructureMapConfigurationPath(); + if (shouldUseStructureMapConfigFileAt(pathToStructureMapConfig)) { - parser.ForEachFile(_log, - delegate(string filename) - { - _log.Try(delegate() - { - ConfigurationParser childParser = ConfigurationParser.FromFile(filename); - list.Add(childParser); - }).AndReportErrorAs(150, filename); - }); + _log.Try(() => + { + ConfigurationParser parser = ConfigurationParser.FromFile(pathToStructureMapConfig); + list.Add(parser); + }).AndReportErrorAs(100, pathToStructureMapConfig); } - - - return list.ToArray(); } private bool shouldUseStructureMapConfigFileAt(string pathToStructureMapConfig) @@ -112,7 +125,7 @@ public void IncludeNode(XmlNode node, string description) { - ConfigurationParser parser = new ConfigurationParser(node); + var parser = new ConfigurationParser(node); parser.Description = description; _parsers.Add(parser); @@ -120,7 +133,7 @@ public static ConfigurationParser[] GetParsers(XmlNode node, GraphLog log) { - ConfigurationParserBuilder builder = new ConfigurationParserBuilder(log); + var builder = new ConfigurationParserBuilder(log); builder.IncludeNode(node, string.Empty); builder.IgnoreDefaultFile = true; Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/CreatePluginFamilyExpression.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -21,20 +21,19 @@ { _pluginType = typeof (PLUGINTYPE); - registry.addExpression(delegate(PluginGraph graph) + registry.addExpression(graph => { PluginFamily family = graph.FindFamily(_pluginType); family.SetScopeTo(_scope); - // TODO: clean up with 3.5 - _children.ForEach(delegate(Action<PluginGraph> action) { action(graph); }); - _alterations.ForEach(delegate(Action<PluginFamily> action) { action(family); }); + _children.ForEach(action => action(graph)); + _alterations.ForEach(action => action(family)); }); } public CreatePluginFamilyExpression<PLUGINTYPE> AddInstances(params Instance[] instances) { - return alterAndContinue(delegate(PluginFamily family) + return alterAndContinue(family => { foreach (Instance instance in instances) { @@ -44,7 +43,6 @@ } - // TODO: 3.5, Try alterAndContinue(f => {}); private CreatePluginFamilyExpression<PLUGINTYPE> alterAndContinue(Action<PluginFamily> action) { _alterations.Add(action); @@ -58,7 +56,7 @@ /// <returns></returns> public CreatePluginFamilyExpression<PLUGINTYPE> TheDefaultIs(Instance instance) { - return alterAndContinue(delegate(PluginFamily family) + return alterAndContinue(family => { family.AddInstance(instance); family.DefaultInstanceKey = instance.Name; @@ -67,8 +65,7 @@ public CreatePluginFamilyExpression<PLUGINTYPE> AddInstance(Instance instance) { - return alterAndContinue( - delegate(PluginFamily family) { family.AddInstance(instance); }); + return alterAndContinue(family => family.AddInstance(instance)); } /// <summary> @@ -83,7 +80,7 @@ { ExpressionValidator.ValidatePluggabilityOf(typeof (CONCRETETYPE)).IntoPluginType(_pluginType); - return alterAndContinue(delegate(PluginFamily family) + return alterAndContinue(family => { Plugin plugin = family.Plugins.FindOrCreate(typeof (CONCRETETYPE), true); family.DefaultInstanceKey = plugin.ConcreteKey; @@ -100,7 +97,7 @@ /// <returns></returns> public CreatePluginFamilyExpression<PLUGINTYPE> CacheBy(InstanceScope scope) { - return alterAndContinue(delegate(PluginFamily family) { family.SetScopeTo(scope); }); + return alterAndContinue(family => family.SetScopeTo(scope)); } /// <summary> @@ -109,8 +106,7 @@ /// <returns></returns> public CreatePluginFamilyExpression<PLUGINTYPE> AsSingletons() { - _alterations.Add( - delegate(PluginFamily family) { family.SetScopeTo(InstanceScope.Singleton); }); + _alterations.Add(family => family.SetScopeTo(InstanceScope.Singleton)); return this; } @@ -118,9 +114,9 @@ public CreatePluginFamilyExpression<PLUGINTYPE> OnCreation(Action<PLUGINTYPE> handler) { _children.Add( - delegate(PluginGraph graph) + graph => { - Func<object, object> function = delegate(object target) + Func<object, object> function = target => { handler((PLUGINTYPE) target); return target; @@ -136,9 +132,9 @@ public CreatePluginFamilyExpression<PLUGINTYPE> EnrichWith(EnrichmentHandler<PLUGINTYPE> handler) { _children.Add( - delegate(PluginGraph graph) + graph => { - Func<object, object> function = delegate(object target) { return handler((PLUGINTYPE) target); }; + Func<object, object> function = target => handler((PLUGINTYPE) target); PluginTypeInterceptor interceptor = new PluginTypeInterceptor(typeof (PLUGINTYPE), function); graph.InterceptorLibrary.AddInterceptor(interceptor); @@ -157,7 +153,7 @@ ExpressionValidator.ValidatePluggabilityOf(typeof (CONCRETETYPE)).IntoPluginType(typeof (PLUGINTYPE)); _alterations.Add( - delegate(PluginFamily family) + family => { Plugin plugin = new Plugin(typeof (CONCRETETYPE)); plugin.ConcreteKey = instanceName; @@ -170,13 +166,13 @@ public CreatePluginFamilyExpression<PLUGINTYPE> InterceptConstructionWith(IBuildInterceptor interceptor) { - _alterations.Add(delegate(PluginFamily family) { family.AddInterceptor(interceptor); }); + _alterations.Add(family => family.AddInterceptor(interceptor)); return this; } public CreatePluginFamilyExpression<PLUGINTYPE> AddInstancesFrom(MementoSource source) { - _alterations.Add(delegate(PluginFamily family) { family.AddMementoSource(source); }); + _alterations.Add(family => family.AddMementoSource(source)); return this; } @@ -185,7 +181,7 @@ { ExpressionValidator.ValidatePluggabilityOf(typeof (PLUGGEDTYPE)).IntoPluginType(typeof (PLUGINTYPE)); - _alterations.Add(delegate(PluginFamily family) { family.AddPlugin(typeof (PLUGGEDTYPE), concreteKey); }); + _alterations.Add(family => family.AddPlugin(typeof (PLUGGEDTYPE), concreteKey)); return this; } @@ -197,7 +193,7 @@ public CreatePluginFamilyExpression<PLUGINTYPE> TheDefaultIs(Func<PLUGINTYPE> func) { - ConstructorInstance instance = new ConstructorInstance(delegate() { return func(); }); + ConstructorInstance instance = new ConstructorInstance(() => func()); return TheDefaultIs(instance); } @@ -209,7 +205,7 @@ public CreatePluginFamilyExpression<PLUGINTYPE> AddInstance(Func<PLUGINTYPE> func) { - ConstructorInstance instance = new ConstructorInstance(delegate(){ return func();}); + ConstructorInstance instance = new ConstructorInstance(() => func()); return AddInstance(instance); } Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/GenericFamilyExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/GenericFamilyExpression.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/GenericFamilyExpression.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -19,7 +19,7 @@ private GenericFamilyExpression alterAndContinue(Action<PluginFamily> action) { - _registry.addExpression(delegate(PluginGraph graph) + _registry.addExpression(graph => { PluginFamily family = graph.FindFamily(_pluginType); action(family); @@ -36,7 +36,7 @@ public GenericFamilyExpression TheDefaultIs(Instance instance) { - return alterAndContinue(delegate(PluginFamily family) + return alterAndContinue(family => { family.AddInstance(instance); family.DefaultInstanceKey = instance.Name; @@ -51,17 +51,17 @@ public GenericFamilyExpression AddInstance(Instance instance) { - return alterAndContinue(delegate(PluginFamily family) { family.AddInstance(instance); }); + return alterAndContinue(family => family.AddInstance(instance)); } public GenericFamilyExpression CacheBy(InstanceScope scope) { - return alterAndContinue(delegate(PluginFamily family) { family.SetScopeTo(scope); }); + return alterAndContinue(family => family.SetScopeTo(scope)); } public GenericFamilyExpression OnCreation(Action<object> action) { - Func<object, object> func = delegate(object raw) + Func<object, object> func = raw => { action(raw); return raw; @@ -71,7 +71,7 @@ public GenericFamilyExpression EnrichWith(Func<object, object> func) { - _registry.addExpression(delegate(PluginGraph graph) + _registry.addExpression(graph => { PluginTypeInterceptor interceptor = new PluginTypeInterceptor(_pluginType, func); graph.InterceptorLibrary.AddInterceptor(interceptor); @@ -83,10 +83,7 @@ public GenericFamilyExpression InterceptConstructionWith(IBuildInterceptor interceptor) { - return alterAndContinue(delegate(PluginFamily family) - { - family.AddInterceptor(interceptor); - }); + return alterAndContinue(family => family.AddInterceptor(interceptor)); } public GenericFamilyExpression AddConcreteType(Type concreteType) Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/ProfileExpression.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -61,10 +61,7 @@ /// <returns></returns> public ProfileExpression UseNamedInstance(string instanceKey) { - _registry.addExpression(delegate(PluginGraph graph) - { - graph.SetDefault(_profileName, typeof(T), new ReferencedInstance(instanceKey)); - }); + _registry.addExpression(graph => graph.SetDefault(_profileName, typeof (T), new ReferencedInstance(instanceKey))); return _parent; } @@ -78,10 +75,7 @@ { instance.Name = "Default Instance for Profile " + _profileName; - _registry.addExpression(delegate (PluginGraph graph) - { - graph.SetDefault(_profileName, typeof(T), instance); - }); + _registry.addExpression(graph => graph.SetDefault(_profileName, typeof (T), instance)); return _parent; } @@ -134,10 +128,7 @@ public ProfileExpression Use(Instance instance) { - _registry.addExpression(delegate(PluginGraph graph) - { - graph.SetDefault(_parent._profileName, _pluginType, instance); - }); + _registry.addExpression(graph => graph.SetDefault(_parent._profileName, _pluginType, instance)); return _parent; } Modified: trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/DSL/Expressions/ScanAssembliesExpression.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -19,7 +19,7 @@ public ScanAssembliesExpression(Registry registry) { _registry = registry; - _registry.addExpression(delegate(PluginGraph graph) + _registry.addExpression(graph => { foreach (Assembly assembly in _assemblies) { @@ -68,7 +68,7 @@ public ScanAssembliesExpression AddAllTypesOf<PLUGINTYPE>() { - _registry.addExpression(delegate(PluginGraph pluginGraph) + _registry.addExpression(pluginGraph => { PluginFamily family = pluginGraph.FindFamily(typeof (PLUGINTYPE)); @@ -88,10 +88,7 @@ public ScanAssembliesExpression With(ITypeScanner scanner) { - _registry.addExpression(delegate(PluginGraph graph) - { - graph.Assemblies.AddScanner(scanner); - }); + _registry.addExpression(graph => graph.Assemblies.AddScanner(scanner)); return this; Modified: trunk/Source/StructureMap/Configuration/DSL/Registry.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -89,7 +89,7 @@ ConfiguredInstance instance = new ConfiguredInstance(); addExpression( - delegate(PluginGraph pluginGraph) { pluginGraph.FindFamily(typeof (PLUGINTYPE)).AddInstance(instance); }); + pluginGraph => pluginGraph.FindFamily(typeof (PLUGINTYPE)).AddInstance(instance)); return instance; } @@ -104,7 +104,7 @@ public LiteralInstance AddInstanceOf<PLUGINTYPE>(PLUGINTYPE target) { LiteralInstance literal = new LiteralInstance(target); - _actions.Add(delegate(PluginGraph graph) { graph.FindFamily(typeof (PLUGINTYPE)).AddInstance(literal); }); + _actions.Add(graph => graph.FindFamily(typeof (PLUGINTYPE)).AddInstance(literal)); return literal; } @@ -118,10 +118,7 @@ public PrototypeInstance AddPrototypeInstanceOf<PLUGINTYPE>(PLUGINTYPE prototype) { PrototypeInstance instance = new PrototypeInstance((ICloneable) prototype); - _actions.Add(delegate(PluginGraph graph) - { - graph.FindFamily(typeof (PLUGINTYPE)).AddInstance(instance); - }); + _actions.Add(graph => graph.FindFamily(typeof (PLUGINTYPE)).AddInstance(instance)); return instance; } @@ -129,7 +126,6 @@ /// <summary> /// convenience method for a UserControl /// </summary> - /// <typeparam name="PLUGINTYPE"></typeparam> /// <param name="url"></param> /// <returns></returns> public static UserControlInstance LoadUserControlFrom(string url) @@ -166,14 +162,13 @@ public void RegisterInterceptor(TypeInterceptor interceptor) { - addExpression( - delegate(PluginGraph pluginGraph) { pluginGraph.InterceptorLibrary.AddInterceptor(interceptor); }); + addExpression(pluginGraph => pluginGraph.InterceptorLibrary.AddInterceptor(interceptor)); } public MatchedTypeInterceptor IfTypeMatches(Predicate<Type> match) { MatchedTypeInterceptor interceptor = new MatchedTypeInterceptor(match); - _actions.Add(delegate(PluginGraph graph) { graph.InterceptorLibrary.AddInterceptor(interceptor); }); + _actions.Add(graph => graph.InterceptorLibrary.AddInterceptor(interceptor)); return interceptor; } @@ -191,12 +186,12 @@ public void AddInstanceOf(Type pluginType, Instance instance) { - _actions.Add(delegate(PluginGraph graph) { graph.FindFamily(pluginType).AddInstance(instance); }); + _actions.Add(graph => graph.FindFamily(pluginType).AddInstance(instance)); } public void AddInstanceOf<PLUGINTYPE>(Instance instance) { - _actions.Add(delegate(PluginGraph graph) { graph.FindFamily(typeof (PLUGINTYPE)).AddInstance(instance); }); + _actions.Add(graph => graph.FindFamily(typeof (PLUGINTYPE)).AddInstance(instance)); } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/DSL/RegistryExpressions.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/RegistryExpressions.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/DSL/RegistryExpressions.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -53,7 +53,7 @@ public static ConstructorInstance ConstructedBy<PLUGINTYPE> (Func<PLUGINTYPE> builder) { - return new ConstructorInstance(delegate() { return builder(); }); + return new ConstructorInstance(() => builder()); } public static ReferencedInstance Instance(string referencedKey) Modified: trunk/Source/StructureMap/Configuration/FamilyParser.cs =================================================================== --- trunk/Source/StructureMap/Configuration/FamilyParser.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/FamilyParser.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -7,7 +7,7 @@ namespace StructureMap.Configuration { - public class FamilyParser + public class FamilyParser : XmlConstants { private readonly IGraphBuilder _builder; private readonly XmlMementoCreator _mementoCreator; @@ -21,26 +21,36 @@ public void ParseFamily(XmlElement familyElement) { TypePath typePath = TypePath.CreateFromXmlNode(familyElement); - _builder.ConfigureFamily(typePath, delegate(PluginFamily family) + _builder.ConfigureFamily(typePath, family => { family.DefaultInstanceKey = - familyElement.GetAttribute(XmlConstants.DEFAULT_KEY_ATTRIBUTE); + familyElement.GetAttribute(DEFAULT_KEY_ATTRIBUTE); InstanceScope scope = findScope(familyElement); family.SetScopeTo(scope); attachMementoSource(family, familyElement); - attachPlugins(family, familyElement); + familyElement.ForEachChild(PLUGIN_NODE).Do(element => attachPlugin(element, family)); attachInterceptors(family, familyElement); + attachInstances(family, familyElement, _builder); }); } + private void attachInstances(PluginFamily family, XmlElement familyElement, IGraphBuilder builder) + { + familyElement.ForEachChild(INSTANCE_NODE).Do(element => + { + InstanceMemento memento = _mementoCreator.CreateMemento(element); + family.AddInstance(memento); + }); + } + public void ParseDefaultElement(XmlElement element) { - TypePath pluginTypePath = new TypePath(element.GetAttribute(XmlConstants.PLUGIN_TYPE)); + TypePath pluginTypePath = new TypePath(element.GetAttribute(PLUGIN_TYPE)); - _builder.ConfigureFamily(pluginTypePath, delegate(PluginFamily family) + _builder.ConfigureFamily(pluginTypePath, family => { InstanceScope scope = findScope(element); family.SetScopeTo(scope); @@ -52,9 +62,9 @@ public void ParseInstanceElement(XmlElement element) { - TypePath pluginTypePath = new TypePath(element.GetAttribute(XmlConstants.PLUGIN_TYPE)); + TypePath pluginTypePath = new TypePath(element.GetAttribute(PLUGIN_TYPE)); - _builder.ConfigureFamily(pluginTypePath, delegate(PluginFamily family) + _builder.ConfigureFamily(pluginTypePath, family => { InstanceMemento memento = _mementoCreator.CreateMemento(element); @@ -66,79 +76,52 @@ { InstanceScope returnValue = InstanceScope.PerRequest; - string scopeString = familyElement.GetAttribute(XmlConstants.SCOPE_ATTRIBUTE); - if (!string.IsNullOrEmpty(scopeString)) + familyElement.ForAttributeValue(SCOPE, scope => { - returnValue = (InstanceScope) Enum.Parse(typeof (InstanceScope), scopeString); - } + returnValue = (InstanceScope)Enum.Parse(typeof(InstanceScope), scope); + }); return returnValue; } private void attachMementoSource(PluginFamily family, XmlElement familyElement) { - XmlNode sourceNode = familyElement[XmlConstants.MEMENTO_SOURCE_NODE]; - if (sourceNode != null) + familyElement.IfHasNode(MEMENTO_SOURCE_NODE).Do(node => { - InstanceMemento sourceMemento = new XmlAttributeInstanceMemento(sourceNode); + InstanceMemento sourceMemento = new XmlAttributeInstanceMemento(node); - string context = "MementoSource for " + TypePath.GetAssemblyQualifiedName(family.PluginType) + "\n" + - sourceNode.OuterXml; + string context = string.Format("MementoSource for {0}\n{1}", TypePath.GetAssemblyQualifiedName(family.PluginType), node.OuterXml); _builder.WithSystemObject<MementoSource>(sourceMemento, context, - delegate(MementoSource source) { family.AddMementoSource(source); }); - } + source => family.AddMementoSource(source)); + }); } - private void attachPlugins(PluginFamily family, XmlElement familyElement) - { - // TODO: 3.5 lambda cleanup - XmlNodeList pluginNodes = familyElement.SelectNodes(XmlConstants.PLUGIN_NODE); - foreach (XmlElement pluginElement in pluginNodes) - { - attachPlugin(pluginElement, family); - } - } - private void attachPlugin(XmlElement pluginElement, PluginFamily family) { TypePath pluginPath = TypePath.CreateFromXmlNode(pluginElement); - string concreteKey = pluginElement.GetAttribute(XmlConstants.CONCRETE_KEY_ATTRIBUTE); + string concreteKey = pluginElement.GetAttribute(CONCRETE_KEY_ATTRIBUTE); string context = "creating a Plugin for " + family.PluginType.AssemblyQualifiedName; - _builder.WithType(pluginPath, context, delegate(Type pluggedType) + _builder.WithType(pluginPath, context, pluggedType => { Plugin plugin = new Plugin(pluggedType, concreteKey); family.AddPlugin(plugin); - foreach ( - XmlElement setterElement in pluginElement.ChildNodes) - { - string setterName = - setterElement.GetAttribute("Name"); - plugin.Setters.Add(setterName); - } + pluginElement.ForTextInChild("Setter/@Name").Do(prop => plugin.Setters.Add(prop)); + }); } - // TODO: 3.5 lambda cleanup private void attachInterceptors(PluginFamily family, XmlElement familyElement) { - XmlNode interceptorChainNode = familyElement[XmlConstants.INTERCEPTORS_NODE]; - if (interceptorChainNode == null) + string contextBase = string.Format("creating an InstanceInterceptor for {0}\n", TypePath.GetAssemblyQualifiedName(family.PluginType)); + familyElement.ForEachChild("*/Interceptor").Do(element => { - return; - } - - string contextBase = "creating an InstanceInterceptor for " + - TypePath.GetAssemblyQualifiedName(family.PluginType) + "\n"; - foreach (XmlNode interceptorNode in interceptorChainNode.ChildNodes) - { - XmlAttributeInstanceMemento interceptorMemento = new XmlAttributeInstanceMemento(interceptorNode); - - string context = contextBase + interceptorNode.OuterXml; + var interceptorMemento = new XmlAttributeInstanceMemento(element); + string context = contextBase + element.OuterXml; _builder.WithSystemObject<IBuildInterceptor>(interceptorMemento, context, - delegate(IBuildInterceptor interceptor) { family.AddInterceptor(interceptor); }); - } + interceptor => family.AddInterceptor(interceptor)); + }); } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/ProfileAndMachineParser.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ProfileAndMachineParser.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/ProfileAndMachineParser.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -1,3 +1,4 @@ +using System; using System.Xml; using StructureMap.Graph; using StructureMap.Pipeline; @@ -5,8 +6,7 @@ namespace StructureMap.Configuration { - // TODO: 3.5 cleanup - public class ProfileAndMachineParser + public class ProfileAndMachineParser : XmlConstants { private readonly XmlMementoCreator _creator; private readonly IGraphBuilder _graphBuilder; @@ -23,57 +23,47 @@ public void Parse() { - // TODO: 3.5 cleanup - XmlNode defaultProfileNode = _structureMapNode.Attributes.GetNamedItem(XmlConstants.DEFAULT_PROFILE); - if (defaultProfileNode != null) - { - _profileBuilder.SetDefaultProfileName(defaultProfileNode.InnerText); - } + _structureMapNode.ForAttributeValue(DEFAULT_PROFILE, profileName => _profileBuilder.SetDefaultProfileName(profileName)); - foreach (XmlElement profileElement in findNodes(XmlConstants.PROFILE_NODE)) + forEachNode(PROFILE_NODE).Do(element => { - string profileName = profileElement.GetAttribute(XmlConstants.NAME); + string profileName = element.GetAttribute(NAME); _profileBuilder.AddProfile(profileName); - writeOverrides(profileElement, - delegate(string fullName, string defaultKey) { _profileBuilder.OverrideProfile(new TypePath(fullName), defaultKey); }, profileName); - } + writeOverrides(element, + (fullName, defaultKey) => _profileBuilder.OverrideProfile(new TypePath(fullName), defaultKey), profileName); + }); - foreach (XmlElement machineElement in findNodes(XmlConstants.MACHINE_NODE)) + + forEachNode(MACHINE_NODE).Do(element => { - string machineName = machineElement.GetAttribute(XmlConstants.NAME); - string profileName = machineElement.GetAttribute(XmlConstants.PROFILE_NODE); + string machineName = element.GetAttribute(NAME); + string profileName = element.GetAttribute(PROFILE_NODE); _profileBuilder.AddMachine(machineName, profileName); - writeOverrides(machineElement, - delegate(string fullName, string defaultKey) { _profileBuilder.OverrideMachine(new TypePath(fullName), defaultKey); }, machineName); - } + writeOverrides(element, + (fullName, defaultKey) => _profileBuilder.OverrideMachine(new TypePath(fullName), defaultKey), machineName); + }); } private void writeOverrides(XmlElement parentElement, WriteOverride function, string profileName) { - foreach (XmlElement overrideElement in parentElement.SelectNodes(XmlConstants.OVERRIDE)) - { - processOverrideElement(function, overrideElement, profileName); - } + parentElement.ForEachChild(OVERRIDE).Do(element => processOverrideElement(function, element, profileName)); } private void processOverrideElement(WriteOverride function, XmlElement overrideElement, string profileName) { - string fullName = overrideElement.GetAttribute(XmlConstants.TYPE_ATTRIBUTE); + string fullName = overrideElement.GetAttribute(TYPE_ATTRIBUTE); - XmlElement instanceElement = (XmlElement) overrideElement.SelectSingleNode(XmlConstants.INSTANCE_NODE); - if (instanceElement == null) - { - string defaultKey = overrideElement.GetAttribute(XmlConstants.DEFAULT_KEY_ATTRIBUTE); - function(fullName, defaultKey); - } - else - { - createOverrideInstance(fullName, instanceElement, function, profileName); - } + overrideElement.IfHasNode(INSTANCE_NODE) + .Do(element => createOverrideInstance(fullName, element, function, profileName)) + .Else(() => + { + string defaultKey = overrideElement.GetAttribute(DEFAULT_KEY_ATTRIBUTE); + function(fullName, defaultKey); + }); } private void createOverrideInstance(string fullName, XmlElement instanceElement, WriteOverride function, @@ -85,16 +75,16 @@ TypePath familyPath = new TypePath(fullName); - _graphBuilder.ConfigureFamily(familyPath, delegate(PluginFamily family) - { - family.AddInstance(memento); - function(fullName, key); - }); + _graphBuilder.ConfigureFamily(familyPath, family => + { + family.AddInstance(memento); + function(fullName, key); + }); } - private XmlNodeList findNodes(string nodeName) + private XmlExtensions.XmlNodeExpression forEachNode(string xpath) { - return _structureMapNode.SelectNodes(nodeName); + return _structureMapNode.ForEachChild(xpath); } #region Nested type: WriteOverride Modified: trunk/Source/StructureMap/Configuration/ProfileBuilder.cs =================================================================== --- trunk/Source/StructureMap/Configuration/ProfileBuilder.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/ProfileBuilder.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -47,10 +47,10 @@ public void OverrideProfile(TypePath typePath, string instanceKey) { - _pluginGraph.Log.WithType(typePath, "while trying to add an override for a Profile", delegate(Type pluginType) + _pluginGraph.Log.WithType(typePath, "while trying to add an override for a Profile", pluginType => { ReferencedInstance instance = new ReferencedInstance(instanceKey); - _pluginGraph.SetDefault(_lastProfile, pluginType, instance); + _pluginGraph.SetDefault(_lastProfile, pluginType, instance); }); } @@ -72,12 +72,12 @@ } _pluginGraph.Log.WithType(typePath, - "trying to configure a Machine Override", - delegate(Type pluginType) - { - ReferencedInstance instance = new ReferencedInstance(instanceKey); - _profileManager.SetMachineDefault(pluginType, instance); - }); + "trying to configure a Machine Override", + pluginType => + { + ReferencedInstance instance = new ReferencedInstance(instanceKey); + _profileManager.SetMachineDefault(pluginType, instance); + }); } public void SetDefaultProfileName(string profileName) Modified: trunk/Source/StructureMap/Configuration/XmlConstants.cs =================================================================== --- trunk/Source/StructureMap/Configuration/XmlConstants.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Configuration/XmlConstants.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -29,13 +29,8 @@ public const string PLUGIN_NODE = "Plugin"; public const string PLUGIN_TYPE = "PluginType"; public const string PROFILE_NODE = "Profile"; - public const string SCOPE_ATTRIBUTE = "Scope"; + public const string SCOPE = "Scope"; public const string STRUCTUREMAP = "StructureMap"; public const string TYPE_ATTRIBUTE = "Type"; - - - private XmlConstants() - { - } } } \ No newline at end of file Added: trunk/Source/StructureMap/Configuration/XmlExtensions.cs =================================================================== --- trunk/Source/StructureMap/Configuration/XmlExtensions.cs (rev 0) +++ trunk/Source/StructureMap/Configuration/XmlExtensions.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -0,0 +1,103 @@ +using System; +using System.Xml; + +namespace StructureMap.Configuration +{ + public static class XmlExtensions + { + public static XmlTextExpression ForTextInChild(this XmlNode node, string xpath) + { + return new XmlTextExpression(node, xpath); + } + + public static XmlNodeExpression ForEachChild(this XmlNode node, string xpath) + { + return new XmlNodeExpression(node, xpath); + } + + public static void ForAttributeValue(this XmlNode node, string attributeName, Action<string> action) + { + XmlNode attNode = node.Attributes.GetNamedItem(attributeName); + if (attNode != null) + { + action(attNode.InnerText); + } + } + + public static HasXmlElementExpression IfHasNode(this XmlNode node, string xpath) + { + return new HasXmlElementExpression(node, xpath); + } + + public class HasXmlElementExpression + { + private XmlElement _element; + + internal HasXmlElementExpression(XmlNode parent, string xpath) + { + _element = (XmlElement)parent.SelectSingleNode(xpath); + } + + public HasXmlElementExpression Do(Action<XmlElement> action) + { + if (_element != null) + { + action(_element); + } + + return this; + } + + public void Else(Action action) + { + if (_element == null) + { + action(); + } + } + } + + + public class XmlNodeExpression + { + private XmlNodeList _list; + + internal XmlNodeExpression(XmlNode parent, string xpath) + { + _list = parent.SelectNodes(xpath); + } + + public void Do(Action<XmlElement> action) + { + if (_list == null) return; + + foreach (XmlNode node in _list) + { + action((XmlElement)node); + } + } + } + + public class XmlTextExpression + { + private readonly XmlNodeList _list; + + internal XmlTextExpression(XmlNode parent, string attributePath) + { + _list = parent.SelectNodes(attributePath); + } + + public void Do(Action<string> action) + { + if (_list == null) return; + + foreach (XmlNode node in _list) + { + action(node.InnerText); + } + } + } + + + } +} \ No newline at end of file Modified: trunk/Source/StructureMap/Diagnostics/BuildError.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/BuildError.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Diagnostics/BuildError.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.IO; +using StructureMap.Graph; using StructureMap.Pipeline; namespace StructureMap.Diagnostics @@ -76,5 +78,16 @@ get { return _exception; } set { _exception = value; } } + + public void Write(StringWriter writer) + { + string description = ((IDiagnosticInstance)Instance).CreateToken().Description; + + writer.WriteLine(); + writer.WriteLine("-----------------------------------------------------------------------------------------------------"); + writer.WriteLine("Build Error on Instance '{0}' ({1}) in PluginType {2}", Instance.Name, description, TypePath.GetAssemblyQualifiedName(PluginType)); + if (Exception != null) writer.WriteLine(Exception.ToString()); + writer.WriteLine(); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Diagnostics/Doctor.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/Doctor.cs 2008-06-07 22:48:46 UTC (rev 120) +++ trunk/Source/StructureMap/Diagnostics/Doctor.cs 2008-06-15 01:49:31 UTC (rev 121) @@ -1,48 +1,88 @@ using System; using System.Collections.Generic; +using System.Diagnostics; +using System.IO; using System.Text; -using StructureMap.Graph; namespace StructureMap.Diagnostics { - - - public class DoctorReport + public class... [truncated message content] |
From: <jer...@us...> - 2008-07-10 20:49:48
|
Revision: 126 http://structuremap.svn.sourceforge.net/structuremap/?rev=126&view=rev Author: jeremydmiller Date: 2008-07-10 13:49:46 -0700 (Thu, 10 Jul 2008) Log Message: ----------- fixing some crap with profile manager, improvements to diagnostics, little fixes Modified Paths: -------------- trunk/Source/HTML/HTML.csproj trunk/Source/HTML/InjectingServicesAtRuntime.htm trunk/Source/StructureMap/Configuration/DSL/Registry.cs trunk/Source/StructureMap/Container.cs trunk/Source/StructureMap/Diagnostics/TextReportWriter.cs trunk/Source/StructureMap/Diagnostics/ValidationBuildSession.cs trunk/Source/StructureMap/Diagnostics/WhatDoIHaveWriter.cs trunk/Source/StructureMap/ExplicitArgsExpression.cs trunk/Source/StructureMap/Graph/AssemblyScanner.cs trunk/Source/StructureMap/Graph/Constructor.cs trunk/Source/StructureMap/Graph/ITypeScanner.cs trunk/Source/StructureMap/Graph/Plugin.cs trunk/Source/StructureMap/Graph/PluginFamily.cs trunk/Source/StructureMap/Graph/PluginGraph.cs trunk/Source/StructureMap/IContainer.cs trunk/Source/StructureMap/IInstanceFactory.cs trunk/Source/StructureMap/InstanceFactory.cs trunk/Source/StructureMap/ObjectFactory.cs trunk/Source/StructureMap/Pipeline/BuildPolicy.cs trunk/Source/StructureMap/Pipeline/CacheInterceptor.cs trunk/Source/StructureMap/Pipeline/ExplicitArguments.cs trunk/Source/StructureMap/Pipeline/HttpContextBuildPolicy.cs trunk/Source/StructureMap/Pipeline/Instance.cs trunk/Source/StructureMap/Pipeline/LiteralInstance.cs trunk/Source/StructureMap/Pipeline/Profile.cs trunk/Source/StructureMap/Pipeline/ProfileManager.cs trunk/Source/StructureMap/PipelineGraph.cs trunk/Source/StructureMap/Properties/AssemblyInfo.cs trunk/Source/StructureMap/StructureMap.csproj trunk/Source/StructureMap/StructureMapConfiguration.cs trunk/Source/StructureMap.DataAccess/IDatabaseEngine.cs trunk/Source/StructureMap.DataAccess/StructureMap.DataAccess.csproj trunk/Source/StructureMap.Testing/Attributes/PluginFamilyAttributeTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/AddInstanceTester.cs trunk/Source/StructureMap.Testing/Configuration/DSL/RegistryTester.cs trunk/Source/StructureMap.Testing/DataAccess/CommandCollectionTester.cs trunk/Source/StructureMap.Testing/DataAccess/CommandFactoryTester.cs trunk/Source/StructureMap.Testing/DataAccess/DataSessionTester.cs trunk/Source/StructureMap.Testing/DataAccess/ExecutionStates/AutoCommitExecutionStateTester.cs trunk/Source/StructureMap.Testing/DataAccess/ExecutionStates/TransactionalExecutionStateTester.cs trunk/Source/StructureMap.Testing/DataAccess/Parameterization/ParameterTemplateTester.cs trunk/Source/StructureMap.Testing/DataAccess/ReaderSourceCollectionTester.cs trunk/Source/StructureMap.Testing/Examples.cs trunk/Source/StructureMap.Testing/Graph/ContainerTester.cs trunk/Source/StructureMap.Testing/Graph/DefaultConventionScanningTester.cs trunk/Source/StructureMap.Testing/Graph/ExplicitArgumentTester.cs trunk/Source/StructureMap.Testing/Pipeline/ProfileManagerMergeTester.cs trunk/Source/StructureMap.Testing/Pipeline/ProfileManagerTester.cs trunk/Source/StructureMap.Testing/PipelineGraphTester.cs trunk/Source/StructureMap.Testing/StructureMap.Testing.csproj trunk/Source/StructureMap.Testing/TestData/AttributeNormalized.xml trunk/Source/StructureMap.Testing/TestData/DefaultInstance.xml trunk/Source/StructureMap.Testing.Widget/StructureMap.Testing.Widget.csproj trunk/Source/StructureMap.Testing.Widget2/StructureMap.Testing.Widget2.csproj trunk/Source/StructureMap.Testing.Widget3/StructureMap.Testing.Widget3.csproj trunk/Source/StructureMap.Testing.Widget4/StructureMap.Testing.Widget4.csproj trunk/Source/StructureMap.Testing.Widget5/StructureMap.Testing.Widget5.csproj trunk/Source/StructureMap.sln Added Paths: ----------- trunk/Source/StructureMap.DataAccess/structuremap.snk trunk/Source/StructureMap.Testing/Properties/ trunk/Source/StructureMap.Testing/Properties/Settings.Designer.cs trunk/Source/StructureMap.Testing/Properties/Settings.settings trunk/Source/StructureMap.Testing.Widget/structuremap.snk trunk/Source/StructureMap.Testing.Widget2/structuremap.snk trunk/Source/StructureMap.Testing.Widget3/structuremap.snk trunk/Source/StructureMap.Testing.Widget4/structuremap.snk trunk/Source/StructureMap.Testing.Widget5/structuremap.snk Removed Paths: ------------- trunk/Source/HTML/Concepts.htm Deleted: trunk/Source/HTML/Concepts.htm =================================================================== --- trunk/Source/HTML/Concepts.htm 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/HTML/Concepts.htm 2008-07-10 20:49:46 UTC (rev 126) @@ -1,49 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> -<html> - <head> - <title></title> - </head> - <body> - <h3>Patterns and Concepts</h3> - <p> - Object oriented systems are composed of a myriad array of objects communicating - by sending messages to exposed interfaces. To a large degree, the qualities of - an OO design are determined by the structure, organization, and responsibility - assignments of the objects in a system. The qualities of a system most - affected by structure are flexibility, extensibility, maintainability, and - testability. Applications usually meet their demise when the system is - determined to be too difficult or costly to change. The symptoms of a dying - application are a loss of clearly defined structure, an unclear division - of responsibilities in the code, and difficulty testing and troubleshooting the - application. </p> - <p> - Over the years a series of rules and principles have been discovered and - developed to describe well-structured systems. Possibly most important is - <em>Separation of Concerns</em> – pulling separate aspects of the system like - persistence, security, or business logic into separate classes and packages. - Another key concept is the combination of highly cohesive classes in a loosely - coupled structure. The more highly coupled two components of a system are, the - more difficult the system is to maintain, test, and reuse. A class should have a - cohesive set of responsibilities in a narrow domain. In other words, - simpleton classes that do only one thing are much easier to code and test than - <em>God</em> classes that take on far too many unrelated responsibilities. </p> - <p> </p> - <h4>Separation of Concerns</h4> - <h4>Services and Dependencies</h4> - <h4>Dependency Injection</h4> - <h4>Container</h4> - <h4>Service Locator</h4> - <h3>StructureMap Terms</h3> - <h4>PluginType</h4> - <p>Object Oriented Design</p> - <h4>Auto Wiring</h4> - <p>Every "real" IoC container supports the concept of "Auto Wiring." Auto - Wiring simply means that StructureMap can figure out dependency chains for you.</p> - <h4>Instance</h4> - <h4>Scoping</h4> - <h4>PluginFamily</h4> - <h4>Profile</h4> - <h4>Interceptor</h4> - <h4>PostProcessor</h4> - </body> -</html> \ No newline at end of file Modified: trunk/Source/HTML/HTML.csproj =================================================================== --- trunk/Source/HTML/HTML.csproj 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/HTML/HTML.csproj 2008-07-10 20:49:46 UTC (rev 126) @@ -62,7 +62,7 @@ <Content Include="BestPractices.htm" /> <Content Include="ChangingDefaultsAtRuntime.htm" /> <Content Include="CompositeConfiguration.htm" /> - <Content Include="Concepts.htm" /> + <Content Include="Glossary.htm" /> <Content Include="ConcreteTypes.htm" /> <Content Include="ConfigurationArchitecture.htm" /> <Content Include="ConfiguringStructureMap.htm" /> Modified: trunk/Source/HTML/InjectingServicesAtRuntime.htm =================================================================== --- trunk/Source/HTML/InjectingServicesAtRuntime.htm 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/HTML/InjectingServicesAtRuntime.htm 2008-07-10 20:49:46 UTC (rev 126) @@ -4,8 +4,10 @@ <title>Injecting Services or Mocks at Runtime</title> </head> <body> - <h1>Injecting Services, Mocks, and Stubs at Runtime</h1> + <h1>Injecting Modules, Services, Mocks, and Stubs at Runtime</h1> <p>In the beginning (2003), there was attributes and Xml configuration, and I called it good. + Look Ma! I can radically change the behavior of the code without + recompiling, isn't that a marvelous thing? Then we started to use StructureMap on a real project and quickly realized that it would be very useful if we could override some services with mock objects in our unit tests. In later projects I've run into scenarios where it would @@ -21,37 +23,161 @@ normal configuration).</p> <h4>Injecting a Service at Runtime</h4> - <p>In my desktop applications the main form implements some sort of + <p>In my desktop applications the main form usually implements some sort of IApplicationShell interface. I've found it valuable to place the main form itself into StructureMap, as well as several child controls of the main form as well so that various Controllers, Presenters, and Commands can interact with - parts of the main shell. I probably could build the ApplicationShell + parts of the main shell without tight coupling. I probably could build the ApplicationShell itself inside of StructureMap, but the child controls like (I'm making this up) IQueryToolBar or IExplorerPane are easiest to create as part of the - ApplicationShell and loaded later.</p> + ApplicationShell and loaded into StructureMap later.</p> <!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs20 \cf3 public\cf0 \cf3 class\cf0 \cf4 ApplicationShell\cf0 : \cf4 Form\cf0 , \cf4 IApplicationShell\par ??\cf0 \{\par ?? \par ?? \}} --> <div style="font-family: Courier New; font-size: 10pt; color: black; background: white;"> <p style="margin: 0px;"> + </p> +<!-- +{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs20 \cf3 public\cf0 \cf3 class\cf0 \cf4 ApplicationShell\cf0 : \cf4 Form\cf0 , \cf4 IApplicationShell\par ??\cf0 \{\par ?? \cf3 public\cf0 \cf4 IQueryToolBar\cf0 QueryToolBar\par ?? \{\par ?? \cf3 get\par ??\cf0 \{\par ?? \cf3 return\cf0 \cf3 null\cf0 ;\par ?? \}\par ?? \}\par ??\par ?? \cf3 public\cf0 \cf4 IExplorerPane\cf0 ExplorerPane\par ?? \{\par ?? \cf3 get\par ??\cf0 \{\par ?? \cf3 return\cf0 \cf3 null\cf0 ;\par ?? \}\par ?? \}\par ?? \}} +--> + <div style="font-family: Courier New; font-size: 10pt; color: black; background: white;"> + <p style="margin: 0px;"> <span style="color: blue;">public</span> <span style="color: blue;">class</span> - <span style="color: #2b91af;">ApplicationShell</span> : - <span style="color: #2b91af;">Form</span>, <span style="color: #2b91af;"> - IApplicationShell</span></p> - <p style="margin: 0px;"> + <span style="color: #2b91af;">ApplicationShell</span> : + <span style="color: #2b91af;">Form</span>, <span style="color: #2b91af;"> + IApplicationShell</span></p> + <p style="margin: 0px;"> {</p> - <p style="margin: 0px;"> - </p> - <p style="margin: 0px;"> + <p style="margin: 0px;"> + <span style="color: blue;">public</span> + <span style="color: #2b91af;">IQueryToolBar</span> QueryToolBar...</p> + <p style="margin: 0px;"> + <span style="color: blue;">public</span> + <span style="color: #2b91af;">IExplorerPane</span> ExplorerPane...</p> + <p style="margin: 0px;"> + </p> + <p style="margin: 0px;"> }</p> - </div> + </div> <!--EndFragment--> -<p> </p> +</div> +<!--EndFragment--> +<p>Easy enough. The main shell has some controls on it. Now, we may want + a centralized class to govern the behavior of just the query tool bar along the + top of the main form. That class obviously needs to find the IQueryToolBar + on the main form, but I need a clean way of connecting the IQueryToolBar to this + new QueryController class.</p> +<!-- +{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs20 \cf3 public\cf0 \cf3 class\cf0 \cf4 QueryController\par ??\cf0 \{\par ?? \cf3 private\cf0 \cf4 IQueryToolBar\cf0 _toolBar;\par ??\par ?? \cf3 public\cf0 QueryController(\cf4 IQueryToolBar\cf0 toolBar)\par ?? \{\par ?? _toolBar = toolBar;\par ?? \}\par ?? \}} +--> +<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;"> + <p style="margin: 0px;"> + <span style="color: blue;">public</span> <span style="color: blue;"> + class</span> <span style="color: #2b91af;">QueryController</span></p> + <p style="margin: 0px;"> + {</p> + <p style="margin: 0px;"> + <span style="color: blue;">private</span> + <span style="color: #2b91af;">IQueryToolBar</span> _toolBar;</p> + <p style="margin: 0px;"> + </p> + <p style="margin: 0px;"> + <span style="color: blue;">public</span> + QueryController(<span style="color: #2b91af;">IQueryToolBar</span> toolBar)</p> + <p style="margin: 0px;"> + {</p> + <p style="margin: 0px;"> + _toolBar = toolBar;</p> + <p style="margin: 0px;"> + }</p> + <p style="margin: 0px;"> + }</p> +</div> +<!--EndFragment--> +<p>StructureMap is going to build up the QueryController, but it doesn't help to + inject in a new IQueryToolBar that isn't visible anywhere in the application. + We need to get to exactly the right instance of that control. So let's use + the new Inject<T>(T instance) method on ObjectFactory to register the child + controls from the main form.</p> +<!-- +{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green128\blue0;\red43\green145\blue175;\red0\green0\blue255;}??\fs20 \cf3 // Familiar stuff for the average WinForms or WPF developer\par ??\cf0 \cf3 // Create the main form\par ??\cf0 \cf4 ApplicationShell\cf0 shell = \cf5 new\cf0 \cf4 ApplicationShell\cf0 ();\par ??\par ?? \cf3 // Put the main form, and some of its children into StructureMap\par ??\cf0 \cf3 // where other Controllers and Commands can get to them\par ??\cf0 \cf3 // without being coupled to the main form\par ??\cf0 \cf4 ObjectFactory\cf0 .Inject<\cf4 IApplicationShell\cf0 >(shell);\par ?? \cf4 ObjectFactory\cf0 .Inject<\cf4 IQueryToolBar\cf0 >(shell.QueryToolBar);\par ?? \cf4 ObjectFactory\cf0 .Inject<\cf4 IExplorerPane\cf0 >(shell.ExplorerPane);\par ??\par ??\par ?? \cf4 Application\cf0 .Run(shell);} +--> +<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;"> + <p style="margin: 0px;"> + + <span style="color: green;">// Familiar stuff for the average WinForms or WPF + developer</span></p> + <p style="margin: 0px;"> + + <span style="color: green;">// Create the main form</span></p> + <p style="margin: 0px;"> + + <span style="color: #2b91af;">ApplicationShell</span> shell = + <span style="color: blue;">new</span> <span style="color: #2b91af;"> + ApplicationShell</span>();</p> + <p style="margin: 0px;"> + </p> + <p style="margin: 0px;"> + + <span style="color: green;">// Put the main form, and some of its children into + StructureMap</span></p> + <p style="margin: 0px;"> + + <span style="color: green;">// where other Controllers and Commands can get to + them</span></p> + <p style="margin: 0px;"> + + <span style="color: green;">// without being coupled to the main form</span></p> + <p style="margin: 0px;"> + + <span style="color: #2b91af;">ObjectFactory</span>.Inject<<span + style="color: #2b91af;">IApplicationShell</span>>(shell);</p> + <p style="margin: 0px;"> + + <span style="color: #2b91af;">ObjectFactory</span>.Inject<<span + style="color: #2b91af;">IQueryToolBar</span>>(shell.QueryToolBar);</p> + <p style="margin: 0px;"> + + <span style="color: #2b91af;">ObjectFactory</span>.Inject<<span + style="color: #2b91af;">IExplorerPane</span>>(shell.ExplorerPane);</p> + <p style="margin: 0px;"> + </p> + <p style="margin: 0px;"> + </p> + <p style="margin: 0px;"> + + <span style="color: #2b91af;">Application</span>.Run(shell);</p> +</div> +<!--EndFragment--> +<p>I've used this exact strategy on three applications now to great s.Run(shell);</p> +</div> +<!--EndFragment--> +<p>Now, a call to ObjectFactory.GetInstance<QueryController>() will poke the + IQueryToolBar instance we registered above into the constructor of the new + QueryController object. Remember, one of the primary usages of + StructureMap is simply to get the right service dependencies and metadata to the + right concrete classes so you can concentrate on doing QueryController stuff in + the QueryController class instead of bootstrapping all the stuff it needs.</p> +<p>I've used this exact strategy on three applications now to great success. + The previous design had a lot of "thisThing.ThatThing.QueryToolBar" properties + just to get access to the child controls on the main form. It was + devolving into spaghetti code before I adopted the strategy above.</p> +<p>The ObjectFactory.Inject<T>(T instance) method is identical to the older + ObjectFactory.InjectStub<T>(T stub) method. I've marked the older method + as deprecated because I think the name is misleading. </p> +<p>Use this strategy for any type of service or component that you need to inject + into other services, but isn't convenient or possible to build through + StructureMap itself.</p> <h4>Injecting a Mock or a Stub at Runtime</h4> + <p>On its maiden cruise in 2004, my team quickly realized that we needed a way to +On its maiden cruise in 2004, my team quickly realized that we needed a way to + make StructureMap deliver up mock objects in unit tests. It obviously + isn't efficient to muck with an Xml file for each and every unit test that + requires this function, so we wanted a way to temporarily load ObjectFactory up + with a mock object in place of its normal behavior for a given type.</p> <h4></h4> <h4></h4> <h4></h4> <h4></h4> - <h4></h4> </body> </html> \ No newline at end of file Modified: trunk/Source/StructureMap/Configuration/DSL/Registry.cs =================================================================== --- trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Configuration/DSL/Registry.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -31,12 +31,16 @@ internal void ConfigurePluginGraph(PluginGraph graph) { + if (graph.Registries.Contains(this)) return; + graph.Log.StartSource("Registry: " + TypePath.GetAssemblyQualifiedName(GetType())); foreach (Action<PluginGraph> action in _actions) { action(graph); } + + graph.Registries.Add(this); } @@ -193,5 +197,28 @@ { _actions.Add(graph => graph.FindFamily(typeof (PLUGINTYPE)).AddInstance(instance)); } + + public bool Equals(Registry obj) + { + if (ReferenceEquals(null, obj)) return false; + return GetType().Equals(obj.GetType()); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + + if (obj is Registry) return false; + + + if (obj.GetType() != typeof (Registry)) return false; + return Equals((Registry) obj); + } + + public override int GetHashCode() + { + return 0; + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Container.cs =================================================================== --- trunk/Source/StructureMap/Container.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Container.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -82,10 +82,19 @@ { Instance defaultInstance = _pipelineGraph.GetDefault(typeof (PLUGINTYPE)); - ExplicitInstance<PLUGINTYPE> instance = new ExplicitInstance<PLUGINTYPE>(args, defaultInstance); + ExplicitInstance instance = new ExplicitInstance(typeof(PLUGINTYPE), args, defaultInstance); return GetInstance<PLUGINTYPE>(instance); } + public object GetInstance(Type type, ExplicitArguments args) + { + Instance defaultInstance = _pipelineGraph.GetDefault(type); + + Instance instance = new ExplicitInstance(type, args, defaultInstance); + + return GetInstance(type, instance); + } + public void Inject<PLUGINTYPE>(PLUGINTYPE instance) { _pipelineGraph.Inject(instance); @@ -288,6 +297,8 @@ } } + + #endregion private IBuildSession withNewSession() Modified: trunk/Source/StructureMap/Diagnostics/TextReportWriter.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/TextReportWriter.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Diagnostics/TextReportWriter.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -26,6 +26,11 @@ _lines.Add(new TextLine(contents)); } + public void AddContent(string contents) + { + _lines.Add(new PlainLine(contents)); + } + public void Write(StringWriter writer) { CharacterWidth[] widths = CharacterWidth.For(_columnCount); @@ -67,5 +72,27 @@ { Debug.WriteLine(Write()); } + + } + + internal class PlainLine : Line + { + public string Contents { get; set; } + + public PlainLine(string contents) + { + Contents = contents; + } + + public void OverwriteCounts(CharacterWidth[] widths) + { + // no-op + } + + public void Write(TextWriter writer, CharacterWidth[] widths) + { + writer.WriteLine(Contents); + } + } } Modified: trunk/Source/StructureMap/Diagnostics/ValidationBuildSession.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/ValidationBuildSession.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Diagnostics/ValidationBuildSession.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -86,7 +86,7 @@ - void IPipelineGraphVisitor.PluginType(Type pluginType, Instance defaultInstance) + void IPipelineGraphVisitor.PluginType(Type pluginType, Instance defaultInstance, IBuildPolicy policy) { // don't care } Modified: trunk/Source/StructureMap/Diagnostics/WhatDoIHaveWriter.cs =================================================================== --- trunk/Source/StructureMap/Diagnostics/WhatDoIHaveWriter.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Diagnostics/WhatDoIHaveWriter.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -61,7 +61,7 @@ writer.WriteLine(); } - void IPipelineGraphVisitor.PluginType(Type pluginType, Instance defaultInstance) + void IPipelineGraphVisitor.PluginType(Type pluginType, Instance defaultInstance, IBuildPolicy policy) { _writer.AddDivider('-'); string[] contents = new string[]{TypePath.GetAssemblyQualifiedName(pluginType), string.Empty, string.Empty}; @@ -73,6 +73,8 @@ } _writer.AddText(contents); + + _writer.AddContent("Built by: " + policy.ToString()); } private void setContents(string[] contents, Instance instance) Modified: trunk/Source/StructureMap/ExplicitArgsExpression.cs =================================================================== --- trunk/Source/StructureMap/ExplicitArgsExpression.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/ExplicitArgsExpression.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -1,3 +1,4 @@ +using System; using StructureMap.Pipeline; namespace StructureMap @@ -60,5 +61,15 @@ { return _manager.GetInstance<T>(_args); } + + /// <summary> + /// Create an instance using the explicit arguments + /// </summary> + /// <param name="type"></param> + /// <returns></returns> + public object GetInstance(Type type) + { + return _manager.GetInstance(type, _args); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/AssemblyScanner.cs =================================================================== --- trunk/Source/StructureMap/Graph/AssemblyScanner.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Graph/AssemblyScanner.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -29,6 +29,14 @@ { if (!Registry.IsPublicRegistry(type)) return; + foreach (var previous in pluginGraph.Registries) + { + if (previous.GetType().Equals(type)) + { + return; + } + } + Registry registry = (Registry) Activator.CreateInstance(type); registry.ConfigurePluginGraph(pluginGraph); }); Modified: trunk/Source/StructureMap/Graph/Constructor.cs =================================================================== --- trunk/Source/StructureMap/Graph/Constructor.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Graph/Constructor.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -43,6 +43,11 @@ return returnValue; } + public static bool HasConstructors(Type pluggedType) + { + return GetGreediestConstructor(pluggedType) != null; + } + public static ConstructorInfo GetGreediestConstructor(Type pluggedType) { ConstructorInfo returnValue = null; @@ -112,5 +117,10 @@ { return _ctor.GetParameters().Length > 0; } + + public bool IsValid() + { + return _ctor != null; + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/ITypeScanner.cs =================================================================== --- trunk/Source/StructureMap/Graph/ITypeScanner.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Graph/ITypeScanner.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Text; using StructureMap.Configuration.DSL; +using StructureMap.Pipeline; namespace StructureMap.Graph { @@ -19,7 +20,7 @@ Type pluginType = FindPluginType(type); if (pluginType != null) { - registry.ForRequestedType(pluginType).TheDefaultIsConcreteType(type); + registry.ForRequestedType(pluginType).AddInstance(new ConfiguredInstance(type)); } } Modified: trunk/Source/StructureMap/Graph/Plugin.cs =================================================================== --- trunk/Source/StructureMap/Graph/Plugin.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Graph/Plugin.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -123,5 +123,17 @@ { _setters.Visit(arguments); } + + public bool IsValid() + { + return _constructor.IsValid(); + } + + public static Plugin CreateForConcreteType(Type type) + { + if (!Constructor.HasConstructors(type)) return null; + + return new Plugin(type, DEFAULT); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Graph/PluginFamily.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginFamily.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Graph/PluginFamily.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -44,8 +44,11 @@ if (IsConcrete(pluginType)) { - Plugin plugin = new Plugin(pluginType, Plugin.DEFAULT); - Plugins.Add(plugin); + Plugin plugin = Plugin.CreateForConcreteType(pluginType); + if (plugin != null) + { + Plugins.Add(plugin); + } } } Modified: trunk/Source/StructureMap/Graph/PluginGraph.cs =================================================================== --- trunk/Source/StructureMap/Graph/PluginGraph.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Graph/PluginGraph.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -1,5 +1,7 @@ using System; +using System.Collections.Generic; using System.Reflection; +using StructureMap.Configuration.DSL; using StructureMap.Diagnostics; using StructureMap.Interceptors; using StructureMap.Pipeline; @@ -21,6 +23,8 @@ private readonly ProfileManager _profileManager = new ProfileManager(); private readonly bool _useExternalRegistries = true; private bool _sealed = false; + private List<Registry> _registries = new List<Registry>(); + /// <summary> /// Default constructor @@ -37,6 +41,11 @@ _useExternalRegistries = useExternalRegistries; } + public List<Registry> Registries + { + get { return _registries; } + } + public AssemblyScanner Assemblies { get { return _assemblies; } Modified: trunk/Source/StructureMap/IContainer.cs =================================================================== --- trunk/Source/StructureMap/IContainer.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/IContainer.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -66,5 +66,6 @@ ExplicitArgsExpression With<T>(T arg); IExplicitProperty With(string argName); void AssertConfigurationIsValid(); + object GetInstance(Type type, ExplicitArguments args); } } \ No newline at end of file Modified: trunk/Source/StructureMap/IInstanceFactory.cs =================================================================== --- trunk/Source/StructureMap/IInstanceFactory.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/IInstanceFactory.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -23,5 +23,6 @@ InstanceBuilder FindBuilderByConcreteKey(string concreteKey); void ForEachInstance(Action<Instance> action); void ImportFrom(PluginFamily family); + void AcceptVisitor(IPipelineGraphVisitor visitor, Instance defaultInstance); } } \ No newline at end of file Modified: trunk/Source/StructureMap/InstanceFactory.cs =================================================================== --- trunk/Source/StructureMap/InstanceFactory.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/InstanceFactory.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -144,5 +144,11 @@ _instanceBuilders.Add(family.Plugins); family.EachInstance(instance => _instances.Fill(instance.Name, instance)); } + + public void AcceptVisitor(IPipelineGraphVisitor visitor, Instance defaultInstance) + { + visitor.PluginType(PluginType, defaultInstance, _policy); + ForEachInstance(i => visitor.Instance(PluginType, i)); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/ObjectFactory.cs =================================================================== --- trunk/Source/StructureMap/ObjectFactory.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/ObjectFactory.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -53,7 +53,7 @@ /// <returns></returns> public static object FillDependencies(Type type) { - return manager.FillDependencies(type); + return container.FillDependencies(type); } /// <summary> @@ -64,7 +64,7 @@ /// <returns></returns> public static T FillDependencies<T>() { - return (T) manager.FillDependencies(typeof (T)); + return (T) container.FillDependencies(typeof (T)); } [Obsolete("Please use Inject(Type, object) instead.")] @@ -75,7 +75,7 @@ public static void Inject(Type pluginType, object instance) { - manager.Inject(pluginType, instance); + container.Inject(pluginType, instance); } [Obsolete("Please use Inject() instead.")] @@ -86,12 +86,12 @@ public static void Inject<PLUGINTYPE>(PLUGINTYPE instance) { - manager.Inject<PLUGINTYPE>(instance); + container.Inject<PLUGINTYPE>(instance); } public static void Inject<PLUGINTYPE>(string name, PLUGINTYPE instance) { - manager.Inject<PLUGINTYPE>(name, instance); + container.Inject<PLUGINTYPE>(name, instance); } [Obsolete("Please use Inject<PLUGINTYPE>(name) instead.")] @@ -107,18 +107,18 @@ public static string WhatDoIHave() { - return manager.WhatDoIHave(); + return container.WhatDoIHave(); } public static void AssertConfigurationIsValid() { - manager.AssertConfigurationIsValid(); + container.AssertConfigurationIsValid(); } #region Container and setting defaults - private static IContainer manager + private static IContainer container { get { @@ -136,6 +136,7 @@ return _manager; } } + public static string Profile @@ -145,7 +146,7 @@ lock (_lockObject) { _profile = value; - manager.SetDefaultsToProfile(_profile); + container.SetDefaultsToProfile(_profile); } } get { return _profile; } @@ -161,22 +162,22 @@ public static void Configure(Action<Registry> configure) { - manager.Configure(configure); + container.Configure(configure); } public static void SetDefault(Type pluginType, Instance instance) { - manager.SetDefault(pluginType, instance); + container.SetDefault(pluginType, instance); } public static void SetDefault<PLUGINTYPE>(Instance instance) { - manager.SetDefault<PLUGINTYPE>(instance); + container.SetDefault<PLUGINTYPE>(instance); } public static void SetDefault<PLUGINTYPE, CONCRETETYPE>() where CONCRETETYPE : PLUGINTYPE { - manager.SetDefault<PLUGINTYPE, CONCRETETYPE>(); + container.SetDefault<PLUGINTYPE, CONCRETETYPE>(); } @@ -230,7 +231,7 @@ /// <returns></returns> public static object GetInstance(Type pluginType) { - return manager.GetInstance(pluginType); + return container.GetInstance(pluginType); } /// <summary> @@ -240,17 +241,17 @@ /// <returns></returns> public static PLUGINTYPE GetInstance<PLUGINTYPE>() { - return (PLUGINTYPE) manager.GetInstance(typeof (PLUGINTYPE)); + return (PLUGINTYPE) container.GetInstance(typeof (PLUGINTYPE)); } public static object GetInstance(Type TargetType, Instance instance) { - return manager.GetInstance(TargetType, instance); + return container.GetInstance(TargetType, instance); } public static TargetType GetInstance<TargetType>(Instance instance) { - return (TargetType) manager.GetInstance(typeof (TargetType), instance); + return (TargetType) container.GetInstance(typeof (TargetType), instance); } /// <summary> @@ -261,7 +262,7 @@ /// <returns></returns> public static object GetNamedInstance(Type pluginType, string name) { - return manager.GetInstance(pluginType, name); + return container.GetInstance(pluginType, name); } /// <summary> @@ -272,17 +273,17 @@ /// <returns></returns> public static PLUGINTYPE GetNamedInstance<PLUGINTYPE>(string name) { - return (PLUGINTYPE) manager.GetInstance(typeof (PLUGINTYPE), name); + return (PLUGINTYPE) container.GetInstance(typeof (PLUGINTYPE), name); } public static void SetDefaultInstanceName(Type TargetType, string InstanceName) { - manager.SetDefault(TargetType, InstanceName); + container.SetDefault(TargetType, InstanceName); } public static void SetDefaultInstanceName<TargetType>(string InstanceName) { - manager.SetDefault(typeof (TargetType), InstanceName); + container.SetDefault(typeof (TargetType), InstanceName); } /// <summary> @@ -292,7 +293,7 @@ /// <returns></returns> public static IList GetAllInstances(Type pluginType) { - return manager.GetAllInstances(pluginType); + return container.GetAllInstances(pluginType); } /// <summary> @@ -302,7 +303,7 @@ /// <returns></returns> public static IList<PLUGINTYPE> GetAllInstances<PLUGINTYPE>() { - return manager.GetAllInstances<PLUGINTYPE>(); + return container.GetAllInstances<PLUGINTYPE>(); } /// <summary> @@ -313,7 +314,7 @@ /// <returns></returns> public static ExplicitArgsExpression With<T>(T arg) { - return manager.With(arg); + return container.With(arg); } /// <summary> @@ -323,7 +324,7 @@ /// <returns></returns> public static IExplicitProperty With(string argName) { - return manager.With(argName); + return container.With(argName); } Modified: trunk/Source/StructureMap/Pipeline/BuildPolicy.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/BuildPolicy.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Pipeline/BuildPolicy.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -31,5 +31,22 @@ } #endregion + + public bool Equals(BuildPolicy obj) + { + return !ReferenceEquals(null, obj); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + return obj is BuildPolicy; + } + + public override int GetHashCode() + { + return 0; + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Pipeline/CacheInterceptor.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/CacheInterceptor.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Pipeline/CacheInterceptor.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -48,5 +48,10 @@ protected abstract void storeInCache(string instanceKey, Type pluginType, object instance); protected abstract bool isCached(string instanceKey, Type pluginType); protected abstract object retrieveFromCache(string instanceKey, Type pluginType); + + public override string ToString() + { + return GetType().FullName + " / " + _innerPolicy.ToString(); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Pipeline/ExplicitArguments.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/ExplicitArguments.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Pipeline/ExplicitArguments.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -46,6 +46,8 @@ { foreach (KeyValuePair<string, object> arg in _args) { + if (arg.Value == null) continue; + instance.SetProperty(arg.Key, arg.Value.ToString()); instance.Child(arg.Key).Is(arg.Value); } @@ -62,11 +64,11 @@ } } - public class ExplicitInstance<PLUGINTYPE> : ConfiguredInstance + public class ExplicitInstance : ConfiguredInstance { private readonly ExplicitArguments _args; - public ExplicitInstance(ExplicitArguments args, Instance defaultInstance) + public ExplicitInstance(Type pluginType, ExplicitArguments args, Instance defaultInstance) { args.Configure(this); _args = args; @@ -78,7 +80,7 @@ } else { - setPluggedType(typeof(PLUGINTYPE)); + setPluggedType(pluginType); } } Modified: trunk/Source/StructureMap/Pipeline/HttpContextBuildPolicy.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/HttpContextBuildPolicy.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Pipeline/HttpContextBuildPolicy.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -5,6 +5,8 @@ { public class HttpContextBuildPolicy : CacheInterceptor { + private string _prefix = Guid.NewGuid().ToString(); + public static bool HasContext() { return HttpContext.Current != null; @@ -25,9 +27,9 @@ return HttpContext.Current.Items[getKey(instanceKey, pluginType)]; } - private static string getKey(string instanceKey, Type pluginType) + private string getKey(string instanceKey, Type pluginType) { - return string.Format("{0}:{1}", pluginType.AssemblyQualifiedName, instanceKey); + return string.Format("{0}:{1}:{2}", pluginType.AssemblyQualifiedName, instanceKey, _prefix); } protected override CacheInterceptor clone() Modified: trunk/Source/StructureMap/Pipeline/Instance.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/Instance.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Pipeline/Instance.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -33,6 +33,28 @@ set { _name = value; } } + public virtual object Build(Type pluginType, IBuildSession session) + { + object rawValue = createRawObject(pluginType, session); + return applyInterception(rawValue, pluginType); + } + + private object createRawObject(Type pluginType, IBuildSession session) + { + try + { + return build(pluginType, session); + } + catch (StructureMapException ex) + { + throw; + } + catch (Exception ex) + { + throw new StructureMapException(400, ex); + } + } + public InstanceInterceptor Interceptor { get { return _interceptor; } @@ -80,27 +102,7 @@ } } - public virtual object Build(Type pluginType, IBuildSession session) - { - object rawValue = createRawObject(pluginType, session); - return applyInterception(rawValue, pluginType); - } - private object createRawObject(Type pluginType, IBuildSession session) - { - try - { - return build(pluginType, session); - } - catch (StructureMapException ex) - { - throw; - } - catch (Exception ex) - { - throw new StructureMapException(400, ex); - } - } private object applyInterception(object rawValue, Type pluginType) { Modified: trunk/Source/StructureMap/Pipeline/LiteralInstance.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/LiteralInstance.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Pipeline/LiteralInstance.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -43,5 +43,10 @@ { return "Object: " + _object.ToString(); } + + public override string ToString() + { + return string.Format("LiteralInstance: {0}", _object); + } } } \ No newline at end of file Modified: trunk/Source/StructureMap/Pipeline/Profile.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/Profile.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Pipeline/Profile.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -63,6 +63,14 @@ } } + public void Merge(Profile destination) + { + foreach (KeyValuePair<Type, Instance> pair in _instances) + { + destination.SetDefault(pair.Key, pair.Value); + } + } + public void FindMasterInstances(PluginGraph graph) { Dictionary<Type, Instance> master = new Dictionary<Type, Instance>(); @@ -92,5 +100,7 @@ _instances.Add(destinationType, instance); } } + + } } \ No newline at end of file Modified: trunk/Source/StructureMap/Pipeline/ProfileManager.cs =================================================================== --- trunk/Source/StructureMap/Pipeline/ProfileManager.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Pipeline/ProfileManager.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -10,16 +10,31 @@ private readonly Profile _default = new Profile(""); private readonly Profile _machineProfile = new Profile("MACHINE"); private readonly Dictionary<string, Profile> _profiles = new Dictionary<string, Profile>(); - private Profile _currentProfile; + private Profile _currentProfile = new Profile(string.Empty); private string _defaultMachineProfileName; private string _defaultProfileName; + private object _locker = new object(); public ProfileManager() { - _currentProfile = _default; + } + private void setProfile(Profile profile) + { + lock (_locker) + { + _currentProfile = new Profile(profile.Name); + profile.FillAllTypesInto(_currentProfile); + + if (!ReferenceEquals(profile, _default)) + { + _default.FillAllTypesInto(_currentProfile); + } + } + } + public string DefaultMachineProfileName { get { return _defaultMachineProfileName; } @@ -39,14 +54,14 @@ { if (string.IsNullOrEmpty(value)) { - _currentProfile = _default; + setProfile(_default); } else { validateHasProfile(value); - _currentProfile = getProfile(value); - _default.FillAllTypesInto(_currentProfile); + Profile profile = getProfile(value); + setProfile(profile); } } } @@ -70,6 +85,11 @@ { Profile profile = getProfile(profileName); profile.SetDefault(pluginType, instance); + if (profileName == _defaultProfileName || profileName == _defaultMachineProfileName) + { + _default.FillTypeInto(pluginType, instance); + _currentProfile.FillTypeInto(pluginType, instance); + } } private Profile getProfile(string profileName) @@ -95,7 +115,8 @@ public void SetDefault(Type pluginType, Instance instance) { - _default.SetDefault(pluginType, instance); + _currentProfile.SetDefault(pluginType, instance); + _default.FillTypeInto(pluginType, instance); } public Instance GetDefault(Type pluginType) @@ -115,7 +136,7 @@ backfillProfiles(); - _currentProfile = _default; + setProfile(_default); } private void backfillProfiles() @@ -181,6 +202,8 @@ { pair.Value.CopyDefault(basicType, templatedType); } + + CurrentProfile = CurrentProfile; } public void ImportFrom(ProfileManager source) @@ -190,12 +213,16 @@ Profile fromProfile = pair.Value; Profile toProfile = getProfile(pair.Key); - fromProfile.FillAllTypesInto(toProfile); + fromProfile.Merge(toProfile); } - source._default.FillAllTypesInto(_default); + source._default.Merge(_default); + + setProfileDefaults(new GraphLog()); + + CurrentProfile = CurrentProfile; } } } \ No newline at end of file Modified: trunk/Source/StructureMap/PipelineGraph.cs =================================================================== --- trunk/Source/StructureMap/PipelineGraph.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/PipelineGraph.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -10,7 +10,7 @@ public interface IPipelineGraphVisitor { - void PluginType(Type pluginType, Instance defaultInstance); + void PluginType(Type pluginType, Instance defaultInstance, IBuildPolicy policy); void Instance(Type pluginType, Instance instance); } @@ -86,8 +86,7 @@ Type pluginType = pair.Value.PluginType; Instance defaultInstance = _profileManager.GetDefault(pluginType); - visitor.PluginType(pluginType, defaultInstance); - pair.Value.ForEachInstance(instance => visitor.Instance(pluginType, instance)); + pair.Value.AcceptVisitor(visitor, defaultInstance); } @@ -106,7 +105,10 @@ { internal List<Instance> Instances = new List<Instance>(); - public void PluginType(Type pluginType, Instance defaultInstance){} + public void PluginType(Type pluginType, Instance defaultInstance, IBuildPolicy policy) + { + // don't care + } public void Instance(Type pluginType, Instance instance) { Modified: trunk/Source/StructureMap/Properties/AssemblyInfo.cs =================================================================== --- trunk/Source/StructureMap/Properties/AssemblyInfo.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/Properties/AssemblyInfo.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -12,4 +12,8 @@ [assembly : InternalsVisibleTo( "StructureMap.AutoMocking, PublicKey=00240000048000009400000006020000002400005253413100040000010001008d9a2a76e43cd9b1b1944b1f3b489a046b33f0bcd755b25cc5d3ed7b18ded38240d6db7578cd986c72d3feb4f94a7ab26fcfa41e3e4f41cf2c029fba91159db05c44d63f0b2bfac24353a07f4a1230dd3d4240340adafa2275277fa083c75958062cd0e60016701db6af7ae718efdf1e802a840595b49c290964255b3c60c494" + )] +[assembly: + InternalsVisibleTo( + "StructureMap.Testing, PublicKey=00240000048000009400000006020000002400005253413100040000010001008d9a2a76e43cd9b1b1944b1f3b489a046b33f0bcd755b25cc5d3ed7b18ded38240d6db7578cd986c72d3feb4f94a7ab26fcfa41e3e4f41cf2c029fba91159db05c44d63f0b2bfac24353a07f4a1230dd3d4240340adafa2275277fa083c75958062cd0e60016701db6af7ae718efdf1e802a840595b49c290964255b3c60c494" )] \ No newline at end of file Modified: trunk/Source/StructureMap/StructureMap.csproj =================================================================== --- trunk/Source/StructureMap/StructureMap.csproj 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/StructureMap.csproj 2008-07-10 20:49:46 UTC (rev 126) @@ -392,6 +392,7 @@ <None Include="..\structuremap.snk"> <Link>Properties\structuremap.snk</Link> </None> + <None Include="ConfigurationClasses.cd" /> <Compile Include="Configuration\DictionaryReader.cs" /> <Compile Include="Configuration\ITypeReader.cs" /> <Compile Include="Configuration\PrimitiveArrayReader.cs" /> Modified: trunk/Source/StructureMap/StructureMapConfiguration.cs =================================================================== --- trunk/Source/StructureMap/StructureMapConfiguration.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap/StructureMapConfiguration.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -99,6 +99,7 @@ public static PluginGraph GetPluginGraph() { ConfigurationParser[] parsers = _parserBuilder.GetParsers(); + PluginGraphBuilder pluginGraphBuilder = new PluginGraphBuilder(parsers, _registries.ToArray(), _log); return pluginGraphBuilder.Build(); } Modified: trunk/Source/StructureMap.DataAccess/IDatabaseEngine.cs =================================================================== --- trunk/Source/StructureMap.DataAccess/IDatabaseEngine.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap.DataAccess/IDatabaseEngine.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -15,4 +15,6 @@ IDataParameter CreateParameter(string parameterName, DbType dbType, bool isNullable); string GetParameterName(string logicalName); } + + } \ No newline at end of file Modified: trunk/Source/StructureMap.DataAccess/StructureMap.DataAccess.csproj =================================================================== --- trunk/Source/StructureMap.DataAccess/StructureMap.DataAccess.csproj 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap.DataAccess/StructureMap.DataAccess.csproj 2008-07-10 20:49:46 UTC (rev 126) @@ -11,8 +11,7 @@ <AssemblyKeyContainerName> </AssemblyKeyContainerName> <AssemblyName>StructureMap.DataAccess</AssemblyName> - <AssemblyOriginatorKeyFile> - </AssemblyOriginatorKeyFile> + <AssemblyOriginatorKeyFile>structuremap.snk</AssemblyOriginatorKeyFile> <DefaultClientScript>JScript</DefaultClientScript> <DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout> <DefaultTargetSchema>IE50</DefaultTargetSchema> @@ -27,6 +26,7 @@ <UpgradeBackupLocation> </UpgradeBackupLocation> <OldToolsVersion>2.0</OldToolsVersion> + <SignAssembly>true</SignAssembly> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <OutputPath>bin\Debug\</OutputPath> @@ -219,6 +219,7 @@ <Compile Include="MSSQL\MSSQLDatabaseEngine.cs"> <SubType>Code</SubType> </Compile> + <Compile Include="Oracle\OracleDatabaseEngine.cs" /> <Compile Include="ParameterCollection.cs"> <SubType>Code</SubType> </Compile> @@ -302,8 +303,10 @@ </ProjectReference> </ItemGroup> <ItemGroup> + <None Include="structuremap.snk" /> + </ItemGroup> + <ItemGroup> <Folder Include="Exceptions\" /> - <Folder Include="Oracle\" /> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <PropertyGroup> Added: trunk/Source/StructureMap.DataAccess/structuremap.snk =================================================================== (Binary files differ) Property changes on: trunk/Source/StructureMap.DataAccess/structuremap.snk ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Modified: trunk/Source/StructureMap.Testing/Attributes/PluginFamilyAttributeTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Attributes/PluginFamilyAttributeTester.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap.Testing/Attributes/PluginFamilyAttributeTester.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -44,7 +44,7 @@ return new InstanceMemento[0]; } - protected override bool containsKey(string instanceKey) + protected internal override bool containsKey(string instanceKey) { throw new NotImplementedException(); } Modified: trunk/Source/StructureMap.Testing/Configuration/DSL/AddInstanceTester.cs =================================================================== --- trunk/Source/StructureMap.Testing/Configuration/DSL/AddInstanceTester.cs 2008-06-23 17:44:01 UTC (rev 125) +++ trunk/Source/StructureMap.Testing/Configuration/DSL/AddInstanceTester.cs 2008-07-10 20:49:46 UTC (rev 126) @@ -14,7 +14,7 @@ [SetUp] public void SetUp() { - manager = new Container(registry => + container = new Container(registry => { registry.ScanAssemblies().IncludeAssemblyContainingType<ColorWidget>(); @@ -43,19 +43,19 @@ #endregion - private IContainer manager; + private IContainer container; [Test] public void AddAnInstanceWithANameAndAPropertySpecifyingConcreteKey() { - ... [truncated message content] |