Example #1
0
        public static TestConcurrentApp Build(string code,
                                              out IEnumerable <Diagnostic> errors,
                                              bool withInterface = false,
                                              bool withRemote    = false)
        {
            errors = null;

            var config = MockInjector(new Options
            {
                GenerateInterface = withInterface,
                GenerateRemote    = withRemote,
            });
            var compilation = new ExcessCompilation();

            compilation.addDocument("concurrent-test", code, config);

            Assembly assembly = compilation.build();

            if (assembly == null)
            {
                errors = compilation.errors();

                //debug
                StringBuilder errorLines = new StringBuilder();
                foreach (var error in errors)
                {
                    errorLines.AppendLine(error.ToString());
                }

                var errorString = errorLines.ToString();
                return(null);
            }

            var types  = new FactoryMap();
            var result = new TestConcurrentApp(types);

            foreach (var type in assembly.GetTypes())
            {
                var attributes = type.CustomAttributes;
                if (!attributes.Any(attr => attr.AttributeType == typeof(ConcurrentAttribute)))
                {
                    continue;
                }

                var typeName = type.ToString();
                if (attributes.Any(attr => attr.AttributeType == typeof(ConcurrentSingleton)))
                {
                    result.AddSingleton(typeName, (IConcurrentObject)Activator.CreateInstance(type));
                    continue;
                }

                var useParameterLess = type.GetConstructors().Length == 0;
                if (!useParameterLess)
                {
                    useParameterLess = type.GetConstructor(new Type[] { }) != null;
                }

                types[typeName] = (app, args) =>
                {
                    if (useParameterLess)
                    {
                        return((IConcurrentObject)Activator.CreateInstance(type));
                    }

                    var ctor = type.GetConstructor(args
                                                   .Select(arg => arg.GetType())
                                                   .ToArray());

                    if (ctor != null)
                    {
                        return((IConcurrentObject)ctor.Invoke(args));
                    }

                    throw new InvalidOperationException("unable to find a constructor");
                };
            }

            return(result);
        }