コード例 #1
0
        public async Task <TResponse> ExecuteCommand <TRequest, TResponse>(TRequest command, CancellationToken cancellationToken) where TRequest : ICommand
        {
            AnnounceExecuting(command);
            TResponse response;

            if (!_resolver.IsRegistered <ICommandHandler <TRequest, TResponse> >())
            {
                AnnounceNoHandlerFound(command);
                throw new Exception($"No handler could be found for {command.GetType().Name}");
            }

            var handler = _resolver.Resolve <ICommandHandler <TRequest, TResponse> >();

            AnnounceHandlerFound(command, handler);

            var stopwatch = Stopwatch.StartNew();

            try
            {
                response = await handler.Handle(command, cancellationToken);
            }
            catch (Exception e)
            {
                AnnounceFailed(handler, command, e);
                throw;
            }
            stopwatch.Stop();

            AnnounceExecuted(command, handler, stopwatch.ElapsedMilliseconds);
            return(response);
        }
コード例 #2
0
ファイル: Executors.cs プロジェクト: yayaritaa/Europa
        public async Task ExecuteCommand <T>(T command) where T : ICommand
        {
            AnnounceExecuting(command);

            if (!_resolver.IsRegistered <ICommandHandler <T> >())
            {
                AnnounceNoHandlerFound(command);
                throw new Exception($"No handler could be found for {command.GetType().Name}");
            }

            var handler = _resolver.Resolve <ICommandHandler <T> >();

            AnnounceHandlerFound(command, handler);

            var stopwatch = Stopwatch.StartNew();

            try
            {
                await handler.Execute(command);
            }
            catch (Exception e)
            {
                AnnounceFailed(handler, command, e);
                throw;
            }
            stopwatch.Stop();

            AnnounceExecuted(command, handler, stopwatch.ElapsedMilliseconds);
        }
コード例 #3
0
ファイル: ViewModelLocator.cs プロジェクト: EdwOK/Catalog
        public TViewModel Resolve <TViewModel>() where TViewModel : BaseViewModel
        {
            if (!_componentContext.IsRegistered <TViewModel>())
            {
                return(null);
            }

            return(_componentContext.Resolve <TViewModel>());
        }
コード例 #4
0
 public void InjectProperties(IComponentContext context, object instance, IEnumerable <Parameter> parameters)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if (instance == null)
     {
         throw new ArgumentNullException("instance");
     }
     foreach (PropertyInfo info in instance.GetType().GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance))
     {
         Type propertyType = info.PropertyType;
         if (!propertyType.IsValueType && info.GetIndexParameters().Length == 0)
         {
             MethodInfo[] accessors = info.GetAccessors(false);
             if (accessors.Length != 1 || accessors[0].ReturnType == typeof(void))
             {
                 if (context.IsRegistered(propertyType))
                 {
                     object obj2 = context.Resolve(propertyType, parameters);
                     info.SetValue(instance, obj2, null);
                 }
             }
         }
     }
 }
コード例 #5
0
        public static void InjectProperties(IComponentContext context, object instance, bool overrideSetValues)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            var instanceType = instance.GetType();

            foreach (var property in instanceType
                     .GetTypeInfo().DeclaredProperties
                     .Where(pi => pi.CanWrite))
            {
                var propertyType = property.PropertyType;

                if (propertyType.GetTypeInfo().IsValueType&& !propertyType.GetTypeInfo().IsEnum)
                {
                    continue;
                }

                if (propertyType.IsArray && propertyType.GetElementType().GetTypeInfo().IsValueType)
                {
                    continue;
                }

                if (propertyType.IsGenericEnumerableInterfaceType() && propertyType.GetTypeInfo().GenericTypeArguments.ToArray()[0].GetTypeInfo().IsValueType)
                {
                    continue;
                }

                if (property.GetIndexParameters().Length != 0)
                {
                    continue;
                }

                if (!context.IsRegistered(propertyType))
                {
                    continue;
                }

                if (!property.SetMethod.IsPublic)
                {
                    continue;
                }

                if (!overrideSetValues &&
                    property.CanRead && property.CanWrite &&
                    (property.GetValue(instance, null) != null))
                {
                    continue;
                }

                var propertyValue = context.Resolve(propertyType, new NamedParameter(InstanceTypeNamedParameter, instanceType));
                property.SetValue(instance, propertyValue, null);
            }
        }
コード例 #6
0
        private static async ValueTask <TResponse> ExecutingWithResponseAsync <TRequest, TResponse>(
            ILogger logger,
            IComponentContext componentContext,
            TRequest request,
            CancellationToken cancellationToken = default
            )
            where TRequest : IRequest, new()
            where TResponse : IResponse, new()
        {
            var openType = typeof(IRequestHandlerWithResponseAsync <,>);                  // Generic open type.
            var type     = openType.MakeGenericType(typeof(TRequest), typeof(TResponse)); // Type is your runtime type.

            if (!componentContext.IsRegistered(type))
            {
                logger.LogError("ExecuteAsync: " + type.FullName + " - " + " Request: " + typeof(TRequest).FullName + " Response: " + typeof(TResponse).FullName + " not registered!");
                return(new TResponse());
            }

            try
            {
                var requestHandler = componentContext.Resolve(type);
                var methodInfo     = type.GetMethod("ExecuteAsync");
                //logger.LogTrace("ExecuteAsync: " + openType.Name + " - " + " Request: " + typeof(TRequest).FullName + " Response: " + typeof(TResponse).FullName);
                return(await((ValueTask <TResponse>)methodInfo?.Invoke(requestHandler, new[] { (object)request, cancellationToken })).ConfigureAwait(false));
            }
            catch (Exception ex)
            {
                throw LogExceptionManager.LogException(logger, ex);
            }
        }
        public void InjectProperties(IComponentContext context, object instance, bool overrideSetValues)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (instance == null) throw new ArgumentNullException("instance");

            var instanceType = instance.GetType();

            foreach (var property in instanceType
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(pi => pi.CanWrite))
            {
                var propertyType = property.PropertyType;

                if (propertyType.IsValueType && !propertyType.IsEnum)
                    continue;

                if (property.GetIndexParameters().Length != 0)
                    continue;

                if (!context.IsRegistered(propertyType))
                    continue;

                var accessors = property.GetAccessors(false);
                if (accessors.Length == 1 && accessors[0].ReturnType != typeof(void))
                    continue;

                if (!overrideSetValues &&
                    accessors.Length == 2 &&
                    (property.GetValue(instance, null) != null))
                    continue;

                var propertyValue = context.Resolve(propertyType);
                property.SetValue(instance, propertyValue, null);
            }
        }
コード例 #8
0
        public static void InjectProperties(IComponentContext context, object instance)
        {
            var properties = instance.GetType().GetFields(
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (var fieldInfo in properties)
            {
                var propertyType = fieldInfo.FieldType;
                if (propertyType.IsValueType || !context.IsRegistered(propertyType))
                {
                    continue;
                }

                if (HasImportAttribute(fieldInfo))
                {
                    if (fieldInfo.GetValue(instance) != null)
                    {
                        continue; // do not overwrite existing non-null values
                    }

                    var obj = context.Resolve(propertyType);
                    if (obj == null)
                    {
                        throw new DependencyResolutionException(
                                  $"Unable to resolve dependency import on {instance.GetType()} -> {fieldInfo}");
                    }

                    fieldInfo.SetValue(instance, obj);
                }
            }
        }
コード例 #9
0
        public AutoInjectLoader(IComponentContext container)
        {
            var assemblies = AppDomain
                             .CurrentDomain
                             .GetAssemblies();

            var tuples = (from assembly in assemblies
                          from type in assembly.GetTypes()
                          let shouldInjecteds = GetInjectFields(type).ToList()
                                                where shouldInjecteds.Any()
                                                select new Tuple <Type, IEnumerable <FieldInfo> >(type, shouldInjecteds)).ToList();

            foreach (var tuple in tuples)
            {
                var fields = tuple.Item2;
                foreach (var f in fields)
                {
                    if (container.IsRegistered(f.FieldType))
                    {
                        var fieldInstance = container.Resolve(f.FieldType);
                        f.SetValue(null, fieldInstance);
                    }
                }
            }
        }
コード例 #10
0
        static ParameterInfo[] GetParameterInfos(Type instanceType, IComponentContext context)
        {
            var result = new ParameterInfo[0];

            var emptyConstructorIsExists = false;

            foreach (var constructor in instanceType
                     .GetTypeInfo()
                     .DeclaredConstructors
                     .Where(c => !c.IsStatic && c.IsPublic))
            {
                ParameterInfo[] parameters = constructor.GetParameters();
                if (parameters.Length == 0)
                {
                    emptyConstructorIsExists = true;
                }

                if (!parameters.All(x => x.IsOptional || context.IsRegistered(x.ParameterType)))
                {
                    continue;
                }

                if (parameters.Length > result.Length)
                {
                    result = parameters;
                }
            }

            if (result.Length == 0 && !emptyConstructorIsExists)
            {
                throw new ConfigurationException($"Can not resolve instance: {instanceType}");
            }

            return(result);
        }
コード例 #11
0
 /// <inheritdoc />
 public bool HasRegistration(Type serviceType)
 {
     lock (_lockObject)
     {
         return(_componentContext.IsRegistered(serviceType));
     }
 }
コード例 #12
0
        public override IValidator CreateInstance(Type validatorType)
        {
            if (_context.IsRegistered(validatorType))
            {
                try
                {
                    var result = (IValidator)_context.Resolve(validatorType);

                    if (_logger.IsTraceEnabled)
                    {
                        _logger.Trace("Found validator for model: {0} -> validatorType: {1}", validatorType.GetGenericArguments()[0].FullName, result.GetType().FullName);
                    }

                    return(result);
                }
                catch (Exception err)
                {
                    _logger.Error($"Failed to resolve validator {validatorType.FullName} due to <{err.GetType().FullName}>{err.Message}\n{err.StackTrace}");
                }
            }

            if (_logger.IsTraceEnabled)
            {
                _logger.Trace("No validator found for type {0}. Assuming model is valid.", validatorType.GetGenericArguments()[0].FullName);
            }

            return(null);
        }
        public static void InjectMockProperties <T>(this IComponentContext context, Mock <T> mock)
            where T : class
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (mock == null)
            {
                throw new ArgumentNullException("mock");
            }

            object instance = mock.Object;

            foreach (PropertyInfo propertyInfo in instance.GetType()
                     .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                     .Where(pi => pi.CanWrite))
            {
                Type propertyType = propertyInfo.PropertyType;
                if (!propertyType.Namespace.StartsWith("System.") && context.IsRegistered(propertyType))
                {
                    MethodInfo[] accessors = propertyInfo.GetAccessors(false);
                    if (accessors.Length > 0 && accessors[0].ReturnType != typeof(void) && !accessors[0].ReturnType.IsValueType)
                    {
                        object obj = context.Resolve(propertyType);
                        propertyInfo.SetValue(instance, obj, null);
                    }
                }
            }
        }
コード例 #14
0
        public static void InjectProperties(IComponentContext context, object instance)
        {
            var properties = instance.GetType().GetFields(
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (var fieldInfo in properties)
            {
                var propertyType = fieldInfo.FieldType;
                if (propertyType.IsValueType || !context.IsRegistered(propertyType))
                {
                    continue;
                }

                if (HasImportAttribute(fieldInfo))
                {
                    if (fieldInfo.GetValue(instance) != null)
                    {
                        continue; // do not overwrite existing non-null values
                    }

                    var obj = context.Resolve(propertyType);
                    if (obj == null)
                    {
                        throw new DependencyResolutionException(
                            $"Unable to resolve dependency import on {instance.GetType()} -> {fieldInfo}");
                    }

                    fieldInfo.SetValue(instance, obj);
                }
            }
        }
コード例 #15
0
        public static void InjectProperties(IComponentContext context, object instance, bool overrideSetValues)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            foreach (
                PropertyInfo propertyInfo in
                //BindingFlags.NonPublic flag added for non public properties
                instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                Type propertyType = propertyInfo.PropertyType;
                if ((!propertyType.IsValueType || propertyType.IsEnum) &&
                    (propertyInfo.GetIndexParameters().Length == 0 &&
                     context.IsRegistered(propertyType)))
                {
                    //Changed to GetAccessors(true) to return non public accessors
                    MethodInfo[] accessors = propertyInfo.GetAccessors(true);
                    if ((accessors.Length != 1 ||
                         !(accessors[0].ReturnType != typeof(void))) &&
                        (overrideSetValues || accessors.Length != 2 ||
                         propertyInfo.GetValue(instance, null) == null))
                    {
                        object obj = context.Resolve(propertyType);
                        propertyInfo.SetValue(instance, obj, null);
                    }
                }
            }
        }
コード例 #16
0
        private static TResponse ExecutingWithResponse <TRequest, TResponse>(
            ILogger logger,
            IComponentContext componentContext,
            TRequest request
            )
            where TRequest : IRequest, new()
            where TResponse : IResponse, new()
        {
            var openType = typeof(IRequestHandlerWithResponse <,>);                       // Generic open type.
            var type     = openType.MakeGenericType(typeof(TRequest), typeof(TResponse)); // Type is your runtime type.

            if (!componentContext.IsRegistered(type))
            {
                logger.LogError("Execute: " + type.FullName + " - " + " Request: " + typeof(TRequest).FullName + " Response: " + typeof(TResponse).FullName + " not registered!");
                return(new TResponse());
            }

            try
            {
                var requestHandler = componentContext.Resolve(type);
                var methodInfo     = type.GetMethod("Execute");
                //logger.LogTrace("Execute: " + openType.Name + " - " + " Request: " + typeof(TRequest).FullName + " Response: " + typeof(TResponse).FullName);
                return((TResponse)methodInfo?.Invoke(requestHandler, new[] { (object)request }));
            }
            catch (Exception ex)
            {
                throw LogExceptionManager.LogException(logger, ex);
            }
        }
コード例 #17
0
 public static IEnumerable <TService> ResolvePluginServices <TService>(this IComponentContext context)
 {
     if (!context.IsRegistered <PluginServiceProvider>())
     {
         throw new DependencyResolutionException("Unable to resolve plugins without PluginServiceProvider registered");
     }
     return(context.Resolve <PluginServiceProvider>().GetServices <TService>());
 }
コード例 #18
0
        private static IMediator CreateScopedMediator(IComponentContext scope)
        {
            var mediator = new Mediator(
                type => scope.IsRegistered(type) ? scope.Resolve(type) : null,
                type => (IEnumerable <object>)scope.Resolve(typeof(IEnumerable <>).MakeGenericType(type)));

            return(mediator);
        }
コード例 #19
0
 public object CreateInstance(Type serviceType)
 {
     if (_container.IsRegistered(serviceType))
     {
         return(_container.Resolve(serviceType));
     }
     return(Activator.CreateInstance(serviceType));
 }
コード例 #20
0
 public object GetService(Type serviceType)
 {
     if (!_componentContext.IsRegistered(serviceType))
     {
         return(null);
     }
     return(_componentContext.Resolve(serviceType));
 }
コード例 #21
0
 public override IValidator CreateInstance(Type validatorType)
 {
     if (_context.IsRegistered(validatorType))
     {
         return(_context.Resolve(validatorType) as IValidator);
     }
     return(null);
 }
コード例 #22
0
        public MethodResult PostProcess <TResponse>(TResponse response)
        {
            _logger.Information($@"response: {response.GetType().Name}.");
            var instance = typeof(IPostProcess <>).MakeGenericType(response.GetType());

            if (_container.IsRegistered(instance))
            {
                var transformer = _container.Resolve(instance);
                _logger.Information($@"Transformer: {transformer.GetType().Name}");

                transformer.GetType()
                .GetMethod("Transform", new[] { response.GetType() })
                .Invoke(transformer, new object[] { response });
            }

            return(new MethodResult(MethodResultStates.Successful));
        }
コード例 #23
0
        public TCommandHandler ResolveCommandHandler <TCommandHandler>() where TCommandHandler : class, ICommandHandler
        {
            if (!_componentContext.IsRegistered <TCommandHandler>())
            {
                throw new InvalidOperationException("Handler for this command is not registered");
            }

            return(_componentContext.Resolve <TCommandHandler>());
        }
コード例 #24
0
        public static void InjectProperties(IComponentContext context, object instance, IPropertySelector propertySelector)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }
            if (propertySelector == null)
            {
                throw new ArgumentNullException(nameof(propertySelector));
            }

            var instanceType = instance.GetType();

            foreach (var property in instanceType
                     .GetRuntimeProperties()
                     .Where(pi => pi.CanWrite))
            {
                var propertyType = property.PropertyType;

                if (propertyType.GetTypeInfo().IsValueType&& !propertyType.GetTypeInfo().IsEnum)
                {
                    continue;
                }

                if (propertyType.IsArray && propertyType.GetElementType().GetTypeInfo().IsValueType)
                {
                    continue;
                }

                if (propertyType.IsGenericEnumerableInterfaceType() && propertyType.GetTypeInfo().GenericTypeArguments[0].GetTypeInfo().IsValueType)
                {
                    continue;
                }

                if (property.GetIndexParameters().Length != 0)
                {
                    continue;
                }

                if (!context.IsRegistered(propertyType))
                {
                    continue;
                }

                if (!propertySelector.InjectProperty(property, instance))
                {
                    continue;
                }

                var propertyValue = context.Resolve(propertyType, new NamedParameter(InstanceTypeNamedParameter, instanceType));
                property.SetValue(instance, propertyValue, null);
            }
        }
コード例 #25
0
        public void InjectProperties(IComponentContext context, object instance, bool overrideSetValues)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            var instanceType = instance.GetType();

            foreach (var property in instanceType
                     .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                     .Where(pi => pi.CanWrite))
            {
                var propertyType = property.PropertyType;

                if (propertyType.IsValueType && !propertyType.IsEnum)
                {
                    continue;
                }

                if (propertyType.IsArray && propertyType.GetElementType().IsValueType)
                {
                    continue;
                }

                if (property.GetIndexParameters().Length != 0)
                {
                    continue;
                }

                if (!context.IsRegistered(propertyType))
                {
                    continue;
                }

                var accessors = property.GetAccessors(false);
                if (accessors.Length == 1 && accessors[0].ReturnType != typeof(void))
                {
                    continue;
                }

                if (!overrideSetValues &&
                    accessors.Length == 2 &&
                    (property.GetValue(instance, null) != null))
                {
                    continue;
                }

                var propertyValue = context.Resolve(propertyType);
                property.SetValue(instance, propertyValue, null);
            }
        }
コード例 #26
0
    public void Apply <T>(JsonSerializerOptions options, ObjectMapping <T> objectMapping) where T : class
    {
        defaultObjectMappingConvention.Apply <T>(options, objectMapping);

        // use Autofac to create types that have been registered with it
        if (_container.IsRegistered(objectType))
        {
            objectMapping.MapCreator(o => _container.Resolve <T>());
        }
    }
コード例 #27
0
        private static IAppScope AppScopeResolver(IComponentContext ctx)
        {
            if (ctx.IsRegistered <IAppScope>())
            {
                return(ctx.Resolve <IAppScope>());
            }

            if (ctx.IsRegistered <ILifetimeScope>())
            {
                return(new AppScope(ctx.Resolve <ILifetimeScope>()));
            }

            if (ctx.IsRegistered <AppCore>())
            {
                return(ctx.Resolve <AppCore>());
            }

            return(null);
        }
コード例 #28
0
        /// <summary>
        /// Get associate View to ViewModel
        /// </summary>
        /// <returns>View Instance</returns>
        private Page GetView(Type viewModel)
        {
            var type = viewModel;

            //si se registro el viewmodel y la página a mano, se busca en el diccionario
            if (_map.Keys.Contains(type))
            {
                var viewType = _map[type];

                return(_componentContext.Resolve(viewType) as Page);
            }


            var strViewType = _appConfig.ViewLocatorConvention(type.FullName);

            if (string.IsNullOrEmpty(strViewType))
            {
                throw new Exception($"Can't resolve view {strViewType} from {viewModel} viewModel");
            }

            var asm      = type.Assembly;
            var typePage = asm.GetType(strViewType) ?? throw new KeyNotFoundException($"Inferred View ({strViewType}) Not Found");

            // if (typePage == null) throw new KeyNotFoundException($"Inferred View ({strViewType}) Not Found");

            if (_componentContext.IsRegistered(typePage))
            {
                return(_componentContext.Resolve(typePage) as Page);
            }

            try
            {
                return((Page)asm.CreateInstance(strViewType, true));
            }
            catch (Exception e)
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.WriteLine(e);
                }
                throw;
            }
        }
コード例 #29
0
ファイル: EventDispatcher.cs プロジェクト: MAq2402/PayT
        public IEnumerable DispatchMany(IEvent @event)
        {
            var handlerType = typeof(IEventHandler <>)
                              .MakeGenericType(@event.GetType());

            var collectionType = typeof(IEnumerable <>).MakeGenericType(handlerType);

            return(_context.IsRegistered(handlerType)
                ? _context.Resolve(collectionType) as IEnumerable
                : new List <object>());
        }
コード例 #30
0
 public virtual bool IsRegistered(Type type, string name = null)
 {
     if (string.IsNullOrEmpty(name))
     {
         return(context.IsRegistered(type));
     }
     else
     {
         return(context.IsRegisteredWithName(name, type));
     }
 }
コード例 #31
0
        public override object CreateInstance()
        {
            if (_container.IsRegistered(mappedType))
            {
                return(_container.Resolve(mappedType));
            }

            return(_container.IsRegisteredWithName(mappedType.FullName, mappedType)
                       ? _container.ResolveNamed(mappedType.FullName, mappedType)
                       : base.CreateInstance());
        }
コード例 #32
0
		public T Resolve<T>(params object[] parameters) where T : Control
		{
			if (parameters == null || parameters.Length == 0)
			{
				return Resolve<T>();
			}
			if (!_componentContext.IsRegistered<T>())
			{
				RegisterView<T>();
			}
			return _componentContext.Resolve<T>(parameters.Select(p => new TypedParameter(p.GetType(), p)));
		}
コード例 #33
0
		public void InjectProperties(IComponentContext context, object instance, bool overrideSetValues)
		{
			if (context == null) throw new ArgumentNullException("context");
			if (instance == null) throw new ArgumentNullException("instance");

			var instanceType = instance.GetType();

			foreach (var property in instanceType.GetProperties(
				BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty))
			{
				var propertyType = property.PropertyType;

				if (propertyType.IsValueType && !propertyType.IsEnum)
					continue;

				if (property.GetIndexParameters().Length != 0)
					continue;

				if (!context.IsRegistered(propertyType))
					continue;

				var accessors = property.GetAccessors(false);
				if (accessors.Length == 1 && accessors[0].ReturnType != typeof(void))
					continue;

				if (!overrideSetValues &&
					accessors.Length == 2 &&
					(property.GetValue(instance, null) != null))
					continue;

				IComponentRegistration registration;
				var service = new TypedService(propertyType);
				if (!context.ComponentRegistry.TryGetRegistration(service, out registration))
					throw new ComponentNotRegisteredException(service);

				var lookup = context.ResolveLookup(service, registration, Enumerable.Empty<Parameter>());
				try
				{
					if (lookup.Preparing)
						lookup.SharedInstanceActivation += (s, ea) => property.SetValue(instance, s, null);
					else
					{
						var propertyValue = lookup.Factory();
						property.SetValue(instance, propertyValue, null);
					}
				}
				catch (DependencyResolutionException dre)
				{
					dre.Lookups.Push(lookup);
					throw;
				}
			}
		}
コード例 #34
0
        static void UseMiddlewareFromContainer(this IAppBuilder app, IComponentContext container)
        {
            var services = container.ComponentRegistry.Registrations.SelectMany(r => r.Services)
                .OfType<TypedService>()
                .Where(s => s.ServiceType.IsAssignableTo<OwinMiddleware>() && !s.ServiceType.IsAbstract)
                .Select(service => typeof(AutofacMiddleware<>).MakeGenericType(service.ServiceType))
                .Where(serviceType => !container.IsRegistered(serviceType));

            var typedServices = services.ToArray();
            if (!typedServices.Any()) return;

            foreach (var typedService in typedServices)
                app.Use(typedService);
        }
コード例 #35
0
        public static void InjectProperties(IComponentContext context, object instance, bool overrideSetValues)
        {
            if (context == null) throw new ArgumentNullException(nameof(context));
            if (instance == null) throw new ArgumentNullException(nameof(instance));

            var instanceType = instance.GetType();

            foreach (var property in instanceType
                .GetTypeInfo().DeclaredProperties
                .Where(pi => pi.CanWrite))
            {
                var propertyType = property.PropertyType;

                if (propertyType.GetTypeInfo().IsValueType && !propertyType.GetTypeInfo().IsEnum)
                    continue;

                if (propertyType.IsArray && propertyType.GetElementType().GetTypeInfo().IsValueType)
                    continue;

                if (propertyType.IsGenericEnumerableInterfaceType() && propertyType.GetTypeInfo().GenericTypeArguments.ToArray()[0].GetTypeInfo().IsValueType)
                    continue;

                if (property.GetIndexParameters().Length != 0)
                    continue;

                if (!context.IsRegistered(propertyType))
                    continue;

                if (!property.SetMethod.IsPublic)
                    continue;

                if (!overrideSetValues &&
                    property.CanRead && property.CanWrite &&
                    (property.GetValue(instance, null) != null))
                    continue;

                var propertyValue = context.Resolve(propertyType, new NamedParameter(InstanceTypeNamedParameter, instanceType));
                property.SetValue(instance, propertyValue, null);
            }
        }
コード例 #36
0
        public static void InjectProperties(IComponentContext context, object instance, IPropertySelector propertySelector)
        {
            if (context == null) throw new ArgumentNullException(nameof(context));
            if (instance == null) throw new ArgumentNullException(nameof(instance));
            if (propertySelector == null) throw new ArgumentNullException(nameof(propertySelector));

            var instanceType = instance.GetType();

            foreach (var property in instanceType
                .GetRuntimeProperties()
                .Where(pi => pi.CanWrite))
            {
                var propertyType = property.PropertyType;

                if (propertyType.GetTypeInfo().IsValueType && !propertyType.GetTypeInfo().IsEnum)
                    continue;

                if (propertyType.IsArray && propertyType.GetElementType().GetTypeInfo().IsValueType)
                    continue;

                if (propertyType.IsGenericEnumerableInterfaceType() && propertyType.GetTypeInfo().GenericTypeArguments[0].GetTypeInfo().IsValueType)
                    continue;

                if (property.GetIndexParameters().Length != 0)
                    continue;

                if (!context.IsRegistered(propertyType))
                    continue;

                if (!propertySelector.InjectProperty(property, instance))
                    continue;

                var propertyValue = context.Resolve(propertyType, new NamedParameter(InstanceTypeNamedParameter, instanceType));
                property.SetValue(instance, propertyValue, null);
            }
        }
コード例 #37
0
        public static void Init(DatabaseInitMethod structureBootstrap, 
            IDbContext factory, IComponentContext ctx)
        {
            IndexRepository indexRepo = null;
            if (ctx.IsRegistered<IndexRepository>())
            {
                //cant take from context because IDbContext is initializing
                indexRepo = new IndexRepository(factory, log);
            }

            log.Info(String.Format("Initializing DB {0} {1} index module",
                structureBootstrap, (indexRepo==null?"without":"with")));

            switch (structureBootstrap)
            {
                case DatabaseInitMethod.DoNothing:
                    if(indexRepo!=null)
                    {
                        indexRepo.IndexManagers.ForEach(x => x.Optimize());
                    }
                    break;
                case DatabaseInitMethod.Recreate:
                    var schema = factory.GetSchemaExport();
                    schema.Create(true, true);

                    if (indexRepo != null)
                    {
                        indexRepo.IndexManagers.ForEach(x => x.Fill());
                    }
                   
                    break;
                case DatabaseInitMethod.FailIfInvalid:
                    try
                    {
                        factory.ValidateSchema();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("FailIfInvalid valiadtion failed", ex);
                    }
                    Init(DatabaseInitMethod.DoNothing, factory, ctx);
                    break;
                case DatabaseInitMethod.CreateIfInvalid:
                    var newstructureBootstrapMethod = DatabaseInitMethod.DoNothing;
                    //Test connection
                    try
                    {
                        factory.ValidateSchema();
                        if (indexRepo != null)
                        {
                            indexRepo.IndexManagers.ForEach(x => x.Purge());
                            indexRepo.IndexManagers.ForEach(x => x.Fill());
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Debug("CreateIfInvalid valiadtion failed");
                        log.Debug(ex);
                        newstructureBootstrapMethod = DatabaseInitMethod.Recreate;
                    }
                    Init(newstructureBootstrapMethod, factory, ctx);

                    break;
            }
        }
コード例 #38
0
ファイル: DependencyResolver.cs プロジェクト: asipe/Nucs
 private static IEnumerable<object> GetServices(IComponentContext context, Type serviceType)
 {
     return !context.IsRegistered(serviceType)
        ? Enumerable.Empty<object>()
        : GetServiceList(context, serviceType);
 }