Exemplo n.º 1
0
        public void RegisterHandlers(IIMOwinOptions options, Assembly[] hostAssemblies)
        {
            // memoized
            if (Interlocked.Increment(ref _alreadyRegistered) != 0) return;

            var contractTypes = hostAssemblies
                .SelectMany(x =>
                {
                    try
                    {
                        return x.GetTypes();
                    }
                    catch (ReflectionTypeLoadException ex)
                    {
                        return ex.Types.Where(t => t != null);
                    }
                })
                .Where(x => typeof (IMOwinBehaviorContract).IsAssignableFrom(x))
                .Where(x => !x.IsAbstract);

            Parallel.ForEach(contractTypes, classType =>
            {
                var className = classType.Name;
                if (classType.GetConstructors().All(x => x.GetParameters().Length != 0))
                {
                    throw new InvalidOperationException(string.Format("Type needs parameterless constructor, class:{0}", classType.FullName));
                }
                // ignore
                if (classType.GetCustomAttribute<IgnoreOperationAttribute>(true) != null) return;

                foreach (var methodInfo in classType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                {
                    // property
                    if (methodInfo.IsSpecialName && (methodInfo.Name.StartsWith("set_") || methodInfo.Name.StartsWith("get_")))
                        continue;

                    // ignore
                    if (methodInfo.GetCustomAttribute<IgnoreOperationAttribute>(true) != null) 
                        continue;

                    var methodName = methodInfo.Name;
                    // ignore default methods
                    if (methodName == "Equals" || methodName == "GetHashCode" || methodName == "GetType" || methodName == "ToString") 
                        continue;

                    // create handler
                    var handler = new OperationHandler(classType, methodInfo);
                    lock (_handlers)
                    {
                        var path = new RequestPath(className, methodName);
                        // 簡単化のため duplicate entry ⇒ fail
                        if (_handlers.ContainsKey(path))
                        {
                            throw new InvalidOperationException(string.Format("same class and method is not allowed, class:{0} method:{1}", className, methodName));
                        }
                        _handlers.Add(path, handler);
                    }
                }
            });
        }
Exemplo n.º 2
0
        private static void RegisterBusinessLogic(ContainerBuilder builder, Assembly[] assemblies)
        {
            builder.RegisterAssemblyTypes(assemblies)
                .Where(t => !string.IsNullOrWhiteSpace(t.Namespace) && t.Namespace.StartsWith("ReMi.BusinessLogic"))
                .AsImplementedInterfaces()
                .InstancePerDependency()
                .PropertiesAutowired();

            builder.Register<IApiDescriptionBuilder>(
                c => new ApiDescriptionBuilder(
                    assemblies.SelectMany(a => a.GetTypes().Where(t => typeof(ApiController).IsAssignableFrom(t)).Select(x => x)),
                    assemblies.SelectMany(a => a.GetTypes().Where(t => typeof(ICommand).IsAssignableFrom(t) && t.IsClass).Select(x => x))
                    ))
                .PropertiesAutowired()
                .InstancePerDependency();
        }
 public static void RegisterClients(Assembly[] assemblyToFindTypes, Action<Type, Type> registerTypeForContainer)
 {
     var allTypes = assemblyToFindTypes.SelectMany(a => a.GetTypes());
     var allServiceClientInterfaces =
         allTypes.Where(x => typeof(IServiceClient).IsAssignableFrom(x) && x.IsInterface && x != typeof(IServiceClient)).ToList();
     foreach (var @interface in allServiceClientInterfaces)
     {
         registerTypeForContainer(@interface, allTypes.Where(x => @interface.IsAssignableFrom(x) && x.IsClass).FirstOrDefault());
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Registers CQRS chunks into service container
        /// </summary>
        /// <param name="services">DI container</param>
        /// <param name="assemblies">Assemblies list where is CQRS stuff is placed</param>
        /// <param name="filter">Predicate to filter types you would like to register</param>
        public static IServiceCollection AddCqrsSpirit(this IServiceCollection services, Assembly[] assemblies, Func<Type, bool> filter = null)
        {
            var types = assemblies
                .SelectMany(assembly => assembly.ExportedTypes)
                .Where(t => t.GetTypeInfo().IsPublic);

            if (filter != null)
                types = types.Where(filter);

            return AddCqrsSpirit(services, types.ToArray());
        }
Exemplo n.º 5
0
        public SammyApplication(IKernel kernel, Assembly[] assembly)
        {
            _kernel = kernel;
            var types = assembly.SelectMany<Assembly, Type>(a => a.GetTypes()).ToArray();

            // Should this be off some kind of marker (like HttpApplication)?
            _kernel.Register(AllTypes.From(types).BasedOn<SammyController>());

            // This is getting a bit large - how do we initialize this better?
            Routes = RouteCollector.Collect(_kernel.GetAssignableHandlers(typeof(SammyController)).Select(h => h.Service).ToArray());
        }
Exemplo n.º 6
0
        private static IEnumerable<Type> GetAssemblyTypes(Assembly[] assembliesWithServices)
        {
            var results = new List<Type>();

            try
            {
                results.AddRange(assembliesWithServices.SelectMany(assembly => assembly.GetTypes()));
            }
            catch (Exception)
            {
                // ignored
            }
            return results;
        }
Exemplo n.º 7
0
        public IEnumerable<MethodInfo> GetPublicNoArgExtensionMethods(Assembly[] sourceExtensionMethodSearch)
        {
            if (sourceExtensionMethodSearch == null)
            {
                return new MethodInfo[] { };
            }

            //http://stackoverflow.com/questions/299515/c-sharp-reflection-to-identify-extension-methods
            return sourceExtensionMethodSearch
                .SelectMany(assembly => assembly.GetTypes())
                .Where(type => type.IsSealed && !type.IsGenericType && !type.IsNested)
                .SelectMany(type => type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
                .Where(method => method.IsDefined(typeof(ExtensionAttribute), false))
                .Where(method => method.GetParameters()[0].ParameterType == this.Type);
        }
        public void RegisterAssemblies(Assembly[] assemblies)
        {
            var searchTarget = typeof(IHandler<>);

            var dict = assemblies.SelectMany(a => a.GetTypes())
                .SelectMany(t => t.GetInterfaces()
                                    .Where(i => i.IsGenericType
                                        && (i.GetGenericTypeDefinition() == searchTarget)
                                        && !i.ContainsGenericParameters),
                            (t, i) => new { Key = i.GetGenericArguments()[0], Value = t })
                .GroupBy(x => x.Key, x => x.Value)
                .ToDictionary(g => g.Key, g => g.ToList());

            _subscription = dict; 
        }
Exemplo n.º 9
0
 public static void Register(Assembly[] handlerAssemblies, Assembly[] modelAssemblies)
 {
     foreach (
         var route in
             handlerAssemblies.SelectMany(a => a.GetTypes()).Select(GetBaseRouteAttributeFor).SelectMany(
                 routeInfo => routeInfo).OrderByDescending(x => x.Route))
     {
         Debug.WriteLine(string.Format("[OpenRasta.Routing] Registering route '{0}' named '{1}' with handler '{2}'", route.Route, route.Name, route.HandlerType));
         ResourceSpace.Has.ResourcesOfType(route.HandlerType)
             .AtUri(route.Route).Named(route.Name)
             .HandledBy(route.HandlerType)
             .AsJsonDataContract()
             .And.AsXmlDataContract();
     }
     foreach (var type in modelAssemblies.SelectMany(x => x.GetTypes()))
     {
         Debug.WriteLine(string.Format("[OpenRasta.Routing] Registering  type '{0}'", type));
         ResourceSpace.Has.ResourcesOfType(type)
             .WithoutUri
             .AsJsonDataContract()
             .And.AsXmlDataContract();
     }
 }
Exemplo n.º 10
0
 public static IEnumerable<RouteInfo> GetRouteInfo(Assembly[] handlerAssemblies)
 {
     return handlerAssemblies.SelectMany(a => a.GetTypes()).Select(GetBaseRouteAttributeFor).SelectMany(
         routeInfo => routeInfo);
 }
Exemplo n.º 11
0
        // cache all methods
        public IReadOnlyCollection<KeyValuePair<string, OperationInfo>> RegisterHandler(Assembly[] hostAssemblies)
        {
            if (Interlocked.Increment(ref alreadyRegistered) != 0) return new KeyValuePair<string, OperationInfo>[0];

            var contractTypes = hostAssemblies
                .SelectMany(x =>
                {
                    try
                    {
                        return x.GetTypes();
                    }
                    catch (ReflectionTypeLoadException ex)
                    {
                        return ex.Types.Where(t => t != null);
                    }
                })
                .Where(x => typeof(LightNodeContract).IsAssignableFrom(x))
                .Where(x => !x.IsAbstract);

            Parallel.ForEach(contractTypes, classType =>
            {
                var className = classType.Name;
                if (!classType.GetConstructors().Any(x => x.GetParameters().Length == 0))
                {
                    throw new InvalidOperationException(string.Format("Type needs parameterless constructor, class:{0}", classType.FullName));
                }
                if (classType.GetCustomAttribute<IgnoreOperationAttribute>(true) != null) return; // ignore

                foreach (var methodInfo in classType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (methodInfo.IsSpecialName && (methodInfo.Name.StartsWith("set_") || methodInfo.Name.StartsWith("get_"))) continue; // as property
                    if (methodInfo.GetCustomAttribute<IgnoreOperationAttribute>(true) != null) continue; // ignore

                    var methodName = methodInfo.Name;

                    // ignore default methods
                    if (methodName == "Equals"
                     || methodName == "GetHashCode"
                     || methodName == "GetType"
                     || methodName == "ToString")
                    {
                        continue;
                    }

                    var sw = Stopwatch.StartNew();

                    // create handler
                    var handler = new OperationHandler(options, classType, methodInfo);
                    lock (handlers)
                    {
                        // fail duplicate entry
                        var path = new RequestPath(className, methodName);
                        if (handlers.ContainsKey(path))
                        {
                            throw new InvalidOperationException(string.Format("same class and method is not allowed, class:{0} method:{1}", className, methodName));
                        }
                        handlers.Add(path, handler);
                    }

                    sw.Stop();
                    options.Logger.RegisiterOperation(handler.ClassName, handler.MethodName, sw.Elapsed.TotalMilliseconds);
                }
            });

            // return readonly operation info
            return handlers.Select(x => new KeyValuePair<string, OperationInfo>(x.Key.ToString(), new OperationInfo(x.Value))).ToList().AsReadOnly();
        }
        private static void RegisterAssemblyTypes(ContainerBuilder builder, Assembly[] vuelingAssemblies)
        {
            var vuelingTypes = vuelingAssemblies.SelectMany(a => a.GetTypes())
                .Where(t => !t.IsInterface && !t.IsAbstract).OrderBy(t => t.Name).ToList();
            var interfacesImplements = new Dictionary<Type, Type>();

            Assembly.GetExecutingAssembly().GetTypes().Where(t => !t.IsAbstract).ToList()
                .ForEach(c => RegisterTypeDependencies(c, vuelingTypes, interfacesImplements));

            interfacesImplements.ToList().ForEach(
                delegate(KeyValuePair<Type, Type> ii)
                {

                    builder.RegisterType(ii.Value).As(ii.Key).AsImplementedInterfaces();

                });
        }
Exemplo n.º 13
0
        public static void RegisterHandler(Assembly[] hostAssemblies)
        {
            if (Interlocked.Increment(ref alreadyRegistered) != 0) return;

            var contractTypes = hostAssemblies
                .SelectMany(x => x.GetTypes())
                .Where(x => typeof(LightNodeContract).IsAssignableFrom(x));

            Parallel.ForEach(contractTypes, classType =>
            {
                var className = classType.Name;
                foreach (var methodInfo in classType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (methodInfo.IsSpecialName && (methodInfo.Name.StartsWith("set_") || methodInfo.Name.StartsWith("get_"))) continue; // as property

                    var methodName = methodInfo.Name;

                    // ignore default methods
                    if (methodName == "Equals"
                     || methodName == "GetHashCode"
                     || methodName == "GetType"
                     || methodName == "ToString")
                    {
                        continue;
                    }

                    var handler = new OperationHandler();

                    handler.MethodName = methodName;
                    handler.Arguments = methodInfo.GetParameters();
                    handler.ReturnType = methodInfo.ReturnType;

                    foreach (var argument in handler.Arguments)
                    {
                        if (!AllowRequestType.IsAllowType(argument.ParameterType))
                        {
                            throw new InvalidOperationException(string.Format("parameter is not allowed, class:{0} method:{1} paramName:{2} paramType:{3}",
                                className, methodName, argument.Name, argument.ParameterType.FullName));
                        }
                    }

                    // prepare lambda parameters
                    var envArg = Expression.Parameter(typeof(IDictionary<string, object>), "environment");
                    var envBind = Expression.Bind(typeof(LightNodeContract).GetProperty("Environment"), envArg);
                    var args = Expression.Parameter(typeof(object[]), "args");
                    var parameters = methodInfo.GetParameters()
                        .Select((x, i) => Expression.Convert(Expression.ArrayIndex(args, Expression.Constant(i)), x.ParameterType))
                        .ToArray();

                    // Task or Task<T>
                    if (typeof(Task).IsAssignableFrom(handler.ReturnType))
                    {
                        // (object[] args) => new X().M((T1)args[0], (T2)args[1])...
                        var lambda = Expression.Lambda<Func<IDictionary<string, object>, object[], Task>>(
                            Expression.Call(
                                Expression.MemberInit(Expression.New(classType), envBind),
                                methodInfo,
                                parameters),
                            envArg, args);

                        if (handler.ReturnType.IsGenericType && handler.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
                        {
                            handler.HandlerBodyType = HandlerBodyType.AsyncFunc;
                            handler.MethodAsyncFuncBody = lambda.Compile();

                            lock (taskResultExtractors)
                            {
                                if (!taskResultExtractors.ContainsKey(handler.ReturnType))
                                {
                                    // (object task) => (object)((Task<>).Result)
                                    var taskParameter = Expression.Parameter(typeof(object), "task");
                                    var resultLambda = Expression.Lambda<Func<object, object>>(
                                        Expression.Convert(
                                            Expression.Property(
                                                Expression.Convert(taskParameter, handler.ReturnType),
                                                "Result"),
                                            typeof(object)),
                                        taskParameter);

                                    var compiledResultLambda = resultLambda.Compile();

                                    taskResultExtractors[handler.ReturnType] = compiledResultLambda;
                                }
                            }
                        }
                        else
                        {
                            handler.HandlerBodyType = HandlerBodyType.AsyncAction;
                            handler.MethodAsyncActionBody = lambda.Compile();
                        }
                    }
                    else if (handler.ReturnType == typeof(void)) // of course void
                    {
                        // (object[] args) => { new X().M((T1)args[0], (T2)args[1])... }
                        var lambda = Expression.Lambda<Action<IDictionary<string, object>, object[]>>(
                            Expression.Call(
                                Expression.MemberInit(Expression.New(classType), envBind),
                                methodInfo,
                                parameters),
                            envArg, args);

                        handler.HandlerBodyType = HandlerBodyType.Action;
                        handler.MethodActionBody = lambda.Compile();
                    }
                    else // return T
                    {
                        // (object[] args) => (object)new X().M((T1)args[0], (T2)args[1])...
                        var lambda = Expression.Lambda<Func<IDictionary<string, object>, object[], object>>(
                            Expression.Convert(
                                Expression.Call(
                                    Expression.MemberInit(Expression.New(classType), envBind),
                                    methodInfo,
                                    parameters)
                            , typeof(object)),
                            envArg, args);

                        handler.HandlerBodyType = HandlerBodyType.Func;
                        handler.MethodFuncBody = lambda.Compile();
                    }

                    lock (handlers)
                    {
                        // fail duplicate entry
                        var path = new RequestPath(className, methodName);
                        if (handlers.ContainsKey(path))
                        {
                            throw new InvalidOperationException(string.Format("same class and method is not allowed, class:{0} method:{1}", className, methodName));
                        }
                        handlers.Add(path, handler);
                    }
                }
            });
        }
Exemplo n.º 14
0
        private void SetUpDefaults(Assembly[] assemblies)
        {
            var availableHandlerTypes = FindAvailableHandlerTypes(assemblies).ToList();

            FindSagaIdsFor = GetDefaultFindSagaIdsFor(availableHandlerTypes);

            var streamPersisterType = assemblies.SelectMany(x => x.GetTypes()).FirstOrDefault(x => !x.IsAbstract && typeof(ISagaStreamPersister).IsAssignableFrom(x));

            GetStreamPersister = () =>
                {
                    if (streamPersisterType == null) return null;

                    return Construct(streamPersisterType) as ISagaStreamPersister;
                };

            FindMessageHandler = GetDefaultFindMessageHandler(availableHandlerTypes);

            Construct = GetDefaultConstruct();
        }