Ejemplo n.º 1
0
        public static void Intercept <TService, TInterceptor>(this IRegistrator registrator, object serviceKey = null)
            where TInterceptor : class, IInterceptor
        {
            var serviceType = typeof(TService);

            Type proxyType;

            if (serviceType.IsInterface())
            {
                proxyType = _proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(
                    serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else if (serviceType.IsClass())
            {
                proxyType = _proxyBuilder.CreateClassProxyTypeWithTarget(
                    serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else
            {
                throw new ArgumentException(
                          $"Intercepted service type {serviceType} is not a supported, cause it is nor a class nor an interface");
            }

            registrator.Register(serviceType, proxyType,
                                 made: Made.Of(pt => pt.PublicConstructors().FindFirst(ctor => ctor.GetParameters().Length != 0),
                                               Parameters.Of.Type <IInterceptor[]>(typeof(TInterceptor[]))),
                                 setup: Setup.DecoratorOf(useDecorateeReuse: true, decorateeServiceKey: serviceKey));
        }
        public static void Intercept(this IRegistrator registrator, Type serviceType, Type interceptorType, object serviceKey = null)
        {
            Type proxyType;

            if (serviceType.IsInterface())
            {
                proxyType = ProxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else if (serviceType.IsClass())
            {
                proxyType = ProxyBuilder.CreateClassProxyType(serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else
            {
                throw new ArgumentException($"Intercepted service type {serviceType} is not a supported: it is nor class nor interface");
            }

            Setup decoratorSetup = serviceKey == null
                ? Setup.DecoratorWith(useDecorateeReuse : true)
                : Setup.DecoratorWith(r => serviceKey.Equals(r.ServiceKey), useDecorateeReuse: true);

            registrator.Register(serviceType, proxyType,
                                 made: Made.Of(type => type.GetPublicInstanceConstructors().SingleOrDefault(c => c.GetParameters().Length != 0), Parameters.Of.Type <IInterceptor[]>(interceptorType.MakeArrayType())),
                                 setup: decoratorSetup);
        }
Ejemplo n.º 3
0
        public static void Intercept <TService, TInterceptor>(this IRegistrator registrator, object serviceKey = null)
            where TInterceptor : class, IInterceptor
        {
            var serviceType = typeof(TService);

            Type proxyType;

            if (serviceType.IsInterface())
            {
                proxyType = ProxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(
                    serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else if (serviceType.IsClass())
            {
                proxyType = ProxyBuilder.CreateClassProxyType(
                    serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else
            {
                throw new ArgumentException(string.Format(
                                                "Intercepted service type {0} is not a supported: it is nor class nor interface", serviceType));
            }

            var decoratorSetup = serviceKey == null
                ? Setup.DecoratorWith(useDecorateeReuse : true)
                : Setup.DecoratorWith(r => serviceKey.Equals(r.ServiceKey), useDecorateeReuse: true);

            registrator.Register(serviceType, proxyType,
                                 made: Made.Of(type => type.PublicConstructors().SingleOrDefault(c => c.GetParameters().Length != 0),
                                               Parameters.Of.Type <IInterceptor[]>(typeof(TInterceptor[]))),
                                 setup: decoratorSetup);
        }
Ejemplo n.º 4
0
            public void Dispose()
            {
                var items = _items.Value;

                for (var i = 0; i < items.Length; i++)
                {
                    items[i].Dispose();
                }
                _items.Swap(_ => ArrayTools.Empty <IDisposable>());
            }
Ejemplo n.º 5
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="DynamicArray{T}"/> struct with a specified initial capacity.
        /// </summary>
        /// <param name="capacity">The initial capacity of the list.</param>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is less than 0.</exception>
        public DynamicArray(int capacity)
        {
            if (capacity < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(capacity));
            }

            this._array  = capacity == 0 ? ArrayTools.Empty <T>() : new T[capacity];
            this._length = 0;
        }
        public void DryIoc_can_consume_catalog()
        {
            var registrations = new List <ExportedRegistrationInfo>();

            ComposablePartCatalog catalog = new TypeCatalog(typeof(Yes), typeof(No), typeof(Ok));

            foreach (var part in catalog.Parts)
            {
                var creationInfoField = part.GetType().GetMembers(t => t.DeclaredFields)
                                        .FirstOrDefault(f => f.Name == "_creationInfo")
                                        .ThrowIfNull();
                var creationInfo = creationInfoField.GetValue(part);

                var getPartMethod = creationInfo.GetType().GetMembers(t => t.DeclaredMethods)
                                    .FirstOrDefault(m => m.Name == "GetPartType")
                                    .ThrowIfNull();

                var implementationType = (Type)getPartMethod.Invoke(creationInfo, ArrayTools.Empty <object>());

                ExportInfo[] exports = null;
                foreach (var exportDefinition in part.ExportDefinitions)
                {
                    //string serviceTypeFullName = null;
                    //object exportTypeObject;
                    //if (exportDefinition.Metadata.TryGetValue(CompositionConstants.ExportTypeIdentityMetadataName, out exportTypeObject))
                    //    serviceTypeFullName = (string)exportTypeObject;
                    //var contractName = exportDefinition.ContractName;
                    //var serviceKey = string.Equals(contractName, serviceTypeFullName) ? null : contractName;
                    //var export = new ExportInfo(null, serviceKey) { ServiceTypeFullName = serviceTypeFullName };

                    var serviceInfo = GetServiceorDefault(exportDefinition);
                    var export      = new ExportInfo(serviceInfo.ServiceType, serviceInfo.Details.ServiceKey);

                    exports = exports.AppendOrUpdate(export);
                }

                var registration = new ExportedRegistrationInfo
                {
                    ImplementationType = implementationType,
                    Exports            = exports
                };

                registrations.Add(registration);
            }

            var container = new Container().WithMefAttributedModel();

            container.RegisterExports(registrations);

            container.Resolve <IAnswer <Ok> >();
        }
Ejemplo n.º 7
0
        public static void RegisterInterfaceInterceptor <TService, TInterceptor>(this IRegistrator registrator)
            where TInterceptor : class, IInterceptor
        {
            var serviceType = typeof(TService);

            if (!serviceType.IsInterface)
            {
                throw new ArgumentException($"Intercepted service type {serviceType} is not an interface");
            }

            var proxyType = ProxyBuilder.Value.CreateInterfaceProxyTypeWithTargetInterface(
                serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);

            registrator.Register(serviceType, proxyType,
                                 made: Parameters.Of.Type <IInterceptor[]>(typeof(TInterceptor[])),
                                 setup: Setup.Decorator);
        }
        public static Type CreateProxy(this IRegistrator container, Type serviceType)
        {
            Type proxyType;

            if (serviceType.IsInterface())
            {
                proxyType = ProxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(
                    serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else if (serviceType.IsClass())
            {
                proxyType = ProxyBuilder.CreateClassProxyType(
                    serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else
            {
                throw new ArgumentException(
                          $"Intercepted service type {serviceType} is not a supported: it is nor class nor interface");
            }

            return(proxyType);
        }
Ejemplo n.º 9
0
        public async void Registering_greeting_with_middleware_configuration()
        {
            IContainer container = new Container();

            container.Register <TestGreetingMiddleware>();

            var contextItems = new Dictionary <object, object>();

            HttpContextScopeContext.GetContextItems = () => contextItems;

            using (var server = TestServer.Create(app =>
            {
                app.UseDryIocOwinMiddleware(
                    container.WithMvc(ArrayTools.Empty <Assembly>()),
                    scope => scope.Use(new Greeting {
                    Message = "Hey, DryIoc!"
                }));
            }))
            {
                var response = await server.HttpClient.GetAsync("/");

                StringAssert.Contains("Hey, DryIoc!", response.Content.ReadAsStringAsync().Result);
            }
        }
Ejemplo n.º 10
0
        public async void Configure_container_with_MVC_and_use_OWIN_middleware()
        {
            IContainer container = new Container();

            container.Register <TestGreetingMiddleware>();
            container.Register(Made.Of(() => new Greeting {
                Message = "Hey, DryIoc!"
            }), Reuse.InWebRequest);

            var contextItems = new Dictionary <object, object>();

            HttpContextScopeContext.GetContextItems = () => contextItems;

            using (var server = TestServer.Create(app =>
            {
                container = container.WithMvc(ArrayTools.Empty <Assembly>());
                app.UseDryIocOwinMiddleware(container);
            }))
            {
                var response = await server.HttpClient.GetAsync("/");

                StringAssert.Contains("Hey, DryIoc!", response.Content.ReadAsStringAsync().Result);
            }
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="SpaceOptimalDynamicArray{T}"/> class that is empty.
 /// </summary>
 public SpaceOptimalDynamicArray()
 {
     _blocks = ArrayTools.Empty <T[]>();
 }
Ejemplo n.º 12
0
        public void GetOutDegree_LongLine_IsCorrect()
        {
            var g = new DependencyGraph <int>(i => i == 5 ? new[] { 12, 4 } : i <= 0 ? ArrayTools.Empty <int>() : new[] { i - 1 });

            Assert.That(g.GetOutDegree(5), Is.EqualTo(2));
        }
Ejemplo n.º 13
0
        public void ComputeStronglyConnectedComponents_LongLine_HaveCorrectLength()
        {
            var g   = new DependencyGraph <int>(i => i == 5 ? new[] { 12, 4 } : i <= 0 ? ArrayTools.Empty <int>() : new[] { i - 1 });
            var a   = new TarjanStronglyConnectedComponentsAlgorithm <DependencyGraph <int>, int, DependencyGraph <int> .Edge>(g);
            var scc = a.ComputeStronglyConnectedComponents(100);

            Assert.That(scc.Length, Is.EqualTo(94));
            Assert.That(scc[5].Length, Is.EqualTo(8));
            var scc2 = a.ComputeStronglyConnectedComponents(105);

            Assert.That(scc2.Length, Is.EqualTo(5));
        }
 public Expression ToExpression(Func <object, Expression> fallbackConverter)
 {
     return(New(GetType().GetConstructors()[0], ArrayTools.Empty <Expression>()));
 }
Ejemplo n.º 15
0
        public void Can_use_instance_method_for_service_creation()
        {
            var container = new Container();

            container.Register <ServiceFactory>();
            container.Register <IService>(made: Made.Of(
                                              typeof(ServiceFactory).Method("Create", ArrayTools.Empty <Type>()),
                                              ServiceInfo.Of <ServiceFactory>()));

            var service = container.Resolve <IService>();

            Assert.AreEqual("instance", service.Message);
        }
Ejemplo n.º 16
0
        public void Should_return_null_if_instance_factory_is_not_resolved_on_TryResolve()
        {
            var container = new Container();

            container.Register <IService>(made: Made.Of(
                                              typeof(ServiceFactory).Method("Create", ArrayTools.Empty <Type>()),
                                              ServiceInfo.Of <ServiceFactory>()));

            var service = container.Resolve <IService>(IfUnresolved.ReturnDefault);

            Assert.IsNull(service);
        }
Ejemplo n.º 17
0
        public void Should_throw_if_instance_factory_unresolved()
        {
            var container = new Container();

            container.Register <IService, SomeService>(made: Made.Of(
                                                           r => typeof(ServiceFactory).Method("Create", ArrayTools.Empty <Type>()),
                                                           ServiceInfo.Of <ServiceFactory>()));

            var ex = Assert.Throws <ContainerException>(() =>
                                                        container.Resolve <IService>());

            Assert.AreEqual(Error.UnableToResolveUnknownService, ex.Error);
        }
Ejemplo n.º 18
0
        public void Can_use_static_method_for_service_creation()
        {
            var container = new Container();

            container.Register <SomeService>(made: Made.Of(
                                                 r => r.ImplementationType.Method("Create", ArrayTools.Empty <Type>())));

            var service = container.Resolve <SomeService>();

            Assert.AreEqual("static", service.Message);
        }
Ejemplo n.º 19
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="DynamicArray{T}"/> struct that is empty.
 /// </summary>
 /// <param name="initialize">Must be <c>true</c>.</param>
 /// <remarks>This constructor is a workaround to non-existing default constructors for value types.</remarks>
 public DynamicArray(bool initialize)
 {
     Debug.Assert(initialize);
     this._array  = ArrayTools.Empty <T>();
     this._length = 0;
 }
Ejemplo n.º 20
0
        public static T[] Match2 <T>(this T[] source, Func <T, bool> condition)
        {
            if (source == null || source.Length == 0)
            {
                return(source);
            }

            if (source.Length > 2)
            {
                var matchStart = 0;
                T[] matches    = null;
                var matchFound = false;

                var i = 0;
                while (i < source.Length)
                {
                    matchFound = condition(source[i]);
                    if (!matchFound)
                    {
                        // for accumulated matched items
                        if (i != 0 && i > matchStart)
                        {
                            matches = ArrayTools.AppendTo(source, matchStart, i - matchStart, matches);
                        }
                        matchStart = i + 1; // guess the next match start will be after the non-matched item
                    }

                    ++i;
                }

                // when last match was found but not all items are matched (hence matchStart != 0)
                if (matchFound && matchStart != 0)
                {
                    return(ArrayTools.AppendTo(source, matchStart, i - matchStart, matches));
                }

                if (matches != null)
                {
                    return(matches);
                }

                if (matchStart != 0) // no matches
                {
                    return(ArrayTools.Empty <T>());
                }

                return(source);
            }

            if (source.Length == 2)
            {
                var condition0 = condition(source[0]);
                var condition1 = condition(source[1]);
                return(condition0 && condition1 ? new[] { source[0], source[1] }
                    : condition0 ? new[] { source[0] }
                    : condition1 ? new[] { source[1] }
                    : ArrayTools.Empty <T>());
            }

            return(condition(source[0]) ? source : ArrayTools.Empty <T>());
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method.
        /// </summary>
        /// <param name="assembly">Assembly to register</param>
        /// <param name="config">Additional configuration</param>
        public void RegisterAssemblyByConvention(Assembly assembly, ConventionalRegistrationConfig config)
        {
            var context = new ConventionalRegistrationContext(assembly, this, config);

            foreach (var registerer in _conventionalRegistrars)
            {
                registerer.RegisterAssembly(context);
            }

            if (config.InstallInstallers)
            {
                this.Install(assembly);
            }

            // 这里使用 TPL 并行库的原因是因为存在大量仓储类型与应用服务需要注册,应最大限度利用 CPU 来进行操作
            Parallel.ForEach(_waitRegisterInterceptor, keyValue =>
            {
                var proxyBuilder = new DefaultProxyBuilder();

                Type proxyType;
                if (keyValue.Key.IsInterface)
                {
                    proxyType = proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(keyValue.Key, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
                }
                else if (keyValue.Key.IsClass())
                {
                    proxyType = proxyBuilder.CreateClassProxyTypeWithTarget(keyValue.Key, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
                }
                else
                {
                    throw new ArgumentException($"类型 {keyValue.Value} 不支持进行拦截器服务集成。");
                }

                var decoratorSetup = Setup.DecoratorWith(useDecorateeReuse: true);

                // 使用 ProxyBuilder 创建好的代理类替换原有类型的实现
                IocContainer.Register(keyValue.Key, proxyType,
                                      made: Made.Of(type => type.GetConstructors().SingleOrDefault(c => c.GetParameters().Length != 0),
                                                    Parameters.Of.Type <IInterceptor[]>(request =>
                {
                    var objects = new List <object>();
                    foreach (var interceptor in keyValue.Value)
                    {
                        objects.Add(request.Container.Resolve(interceptor));
                    }

                    return(objects.Cast <IInterceptor>().ToArray());
                }),
                                                    PropertiesAndFields.Auto),
                                      setup: decoratorSetup);
            });

            _waitRegisterInterceptor.Clear();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Ensures that a service always resolves as lazy proxy (uses DefaultProxyBuilder).
        /// </summary>
        /// <param name="registrator">The registrator.</param>
        /// <param name="interfaceType">The type of the interface.</param>
        /// <param name="serviceKey">Optional service key.</param>
        public static IRegistrator ResolveAsLazyViaProxyBuilder(this IRegistrator registrator, Type interfaceType, object serviceKey = null)
        {
            // registration of lazy interceptor
            registrator.Register(typeof(LazyInterceptor <>), setup: Setup.Wrapper, ifAlreadyRegistered: IfAlreadyRegistered.Keep);

            // lazy proxy wrapper
            var proxyBuilder = new DefaultProxyBuilder();
            var proxyType    = proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(interfaceType,
                                                                                        ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);

            // decorator for the generated proxy class
            var decoratorSetup = GetDecoratorSetup(serviceKey);

            // make typeof(LazyInterceptor<interfaceType>[])
            var lazyInterceptorArrayType = typeof(LazyInterceptor <>).MakeGenericType(interfaceType).MakeArrayType();

            // register the proxy class as decorator
            registrator.Register(interfaceType, proxyType,
                                 Reuse.Transient,
                                 setup: decoratorSetup,
                                 made: Made.Of(type => type.PublicConstructors().SingleOrDefault(ctor => ctor.GetParameters().Length != 0),
                                               Parameters.Of
                                               .Type(typeof(IInterceptor[]), lazyInterceptorArrayType)
                                               .Type(interfaceType, r => null)));

            return(registrator);
        }
Ejemplo n.º 23
0
 public object ActivatorCreateInstance()
 {
     return(Activator.CreateInstance(typeof(X),
                                     Activator.CreateInstance(typeof(A), ArrayTools.Empty <object>()),
                                     Activator.CreateInstance(typeof(B), ArrayTools.Empty <object>())));
 }