public static bool TryResolveWithoutException <T>(this IComponentContext context, [NotNullWhen(returnValue: true)] out T?instance) where T : class
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            instance = default(T);

            try
            {
                if (context.TryResolve(typeof(T), out object?component))
                {
                    instance = (T)component;
                    return(true);
                }

                return(false);
            }
            catch (Exception e)
            {
                if (e is InvalidCastException || e is DependencyResolutionException)
                {
                    return(false);
                }

                throw;
            }
        }
Example #2
0
        public async System.Threading.Tasks.Task DispatchAsync <T>(params T[] events) where T : IEvent
        {
            foreach (var @event in events)
            {
                if (@event == null)
                {
                    throw new ArgumentNullException(nameof(@event), "Event can not be null.");
                }

                var eventType   = @event.GetType();
                var handlerType = typeof(IEventHandler <>).MakeGenericType(eventType);
                _componentContext.TryResolve(handlerType, out var handler);

                if (handler == null)
                {
                    return;
                }

                var method = handler.GetType()
                             .GetRuntimeMethods()
                             .First(x => x.Name.Equals("HandleAsync"));

                await(System.Threading.Tasks.Task) ((dynamic)handler).HandleAsync(@event);
            }
        }
Example #3
0
        public (bool Successful, object Value) Resolve(IComponentContext context, InjectResolverParam param)
        {
            var type = param.Type;
            var attr = param.Attribute;
            var key  = attr.Key;

            if (key != null)
            {
                if (context.TryResolveKeyed(key, type, out var value))
                {
                    return(true, value);
                }

                Assertion.IsTrue(!attr.Required, $"required inject type {type.Name} with key {key} not resolved.");
                return(false, null);
            }

            {
                if (context.TryResolve(type, out var value))
                {
                    return(true, value);
                }

                Assertion.IsTrue(!attr.Required, $"required inject type {type.Name} not resolved.");
                return(false, null);
            }
        }
Example #4
0
        //I need to find out how to get generic handler in Autofac
        public async Task DispatchAsync <T>(params T[] events) where T : IEvent
        {
            foreach (var @event in events)
            {
                if (@event == null)
                {
                    throw new ArgumentNullException(nameof(@event), "Event can not be null.");
                }

                var    eventType   = @event.GetType();
                var    handlerType = typeof(IEventHandler <>).MakeGenericType(eventType);
                object handler;
                _context.TryResolve(handlerType, out handler);

                if (handler == null)
                {
                    return;
                }

                //GetRuntimeMethods() works with .NET Core, otherwise simply use GetMethod()
                var method = handler.GetType()
                             .GetMethods()
                             .First(x => x.Name.Equals("HandleAsync"));

                await(Task) ((dynamic)handler).HandleAsync(@event);

                //var handler2 = _context.Resolve<IEventHandler<T>>();
                //await handler.HandleAsync(@event);
            }
        }
Example #5
0
        /// <summary>
        /// 装配
        /// </summary>
        /// <param name="classType"></param>
        /// <param name="type"></param>
        /// <param name="context"></param>
        /// <param name="typeDescription"></param>
        /// <returns></returns>
        /// <exception cref="DependencyResolutionException"></exception>
        private object Resolve(Type classType, Type type, IComponentContext context, string typeDescription)
        {
            object obj = null;

            if (!string.IsNullOrEmpty(this.Name))
            {
                context.TryResolveKeyed(this.Name, type, out obj);
            }
            else
            {
                if (type.IsGenericEnumerableInterfaceType())
                {
                    var genericType = type.GenericTypeArguments[0];
                    if (genericType.FullName != null && genericType.FullName.StartsWith("System.Lazy`1"))
                    {
                        genericType = genericType.GenericTypeArguments[0];
                    }

                    context.TryResolveKeyed("`1System.Collections.Generic.IEnumerable`1" + genericType.FullName, type, out obj);
                }
                else
                {
                    context.TryResolve(type, out obj);
                }
            }

            if (obj == null && this.Required)
            {
                throw new DependencyResolutionException($"Autowire error,can not resolve class type:{classType.FullName},${typeDescription} name:{type.Name} "
                                                        + (!string.IsNullOrEmpty(this.Name) ? $",with key:[{this.Name}]" : ""));
            }

            return(obj);
        }
Example #6
0
        /// <summary>
        /// The create instance.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <param name="type">
        /// The type.
        /// </param>
        /// <param name="nonPublic">
        /// The non public.
        /// </param>
        /// <returns>
        /// The create instance.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        public static object CreateInstance(this IComponentContext context, Type type, bool nonPublic)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            object res;

            if (context.TryResolve(type, out res))
            {
                return(res);
            }

            var a = new ReflectionActivator(
                type,
                new BindingFlagsConstructorFinder(nonPublic ? BindingFlags.NonPublic : BindingFlags.Public),
                new MostParametersConstructorSelector(),
                new Parameter[] { },
                new Parameter[] { });

            return(a.ActivateInstance(context, new Parameter[] { }));
        }
Example #7
0
 private async Task DispatchAsync(Type handlerType, IEvent @event)
 {
     if (_context.TryResolve(handlerType, out object handler))
     {
         var method = handler.GetType().GetMethod("HandleAsync");
         await(Task) method.Invoke(handler, new object[] { @event });
     }
 }
Example #8
0
        public static bool TryResolve <T>(this IComponentContext componentContext, out T instance)
        {
            var result = componentContext.TryResolve(typeof(T), out var instanceObj);

            instance = (T)instanceObj;

            return(result);
        }
Example #9
0
        public AccountBaseApplication(IComponentContext context)
        {
            if (!context.IsNull())
            {
                if (context.TryResolve(typeof(IConnection), out var connection))
                {
                    Connection = connection as IConnection;
                }

                if (context.TryResolve(typeof(INotifier), out var notifier))
                {
                    Notifier = notifier as INotifier;
                }

                this.context = context;
            }
        }
        public override IValidator CreateInstance(Type validatorType)
        {
            object instance;

            _componentContext.TryResolve(validatorType, out instance);
            var validator = instance as IValidator;

            return(validator);
        }
Example #11
0
        public async Task <TResult> DispatchAsync <TCommand, TResult>(TCommand command) where TCommand : ICommand
        {
            AppAbstractValidation <TCommand> validator;

            if (_context.TryResolve(out validator))
            {
                var validationResult = validator.Validate(command);
                if (!validationResult.IsValid)
                {
                    throw new ValidationException(validationResult.Errors);
                }
            }

            var handler = _context.Resolve <ICommandHandler <TCommand, TResult> >();
            var result  = await handler.ExecuteAsync(command).ConfigureAwait(false);

            return(result);
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="services"></param>
 /// <param name="jsonSerializerSettings"></param>
 public CompactServer(IComponentContext services)
 {
     this.services = services;
     if (!services.TryResolve(out serviceTypes))
     {
         throw new Exception($"Type '{nameof(CompactServerTypes)}' was not registerd in AutoFace. Please register it as instance and add controller types to it.");
     }
     this.jsonSerializerSettings = services.Resolve <JsonSerializerSettings>();
 }
Example #13
0
        public override IValidator CreateInstance(Type validatorType)
        {
            if (_context.TryResolve(validatorType, out var validator))
            {
                return((IValidator)validator);
            }

            return(null);
        }
Example #14
0
        public void Send <T>(T command) where T : ICommand
        {
            ICommandHandler <T> commandHandler;

            if (container.TryResolve(out commandHandler))
            {
                commandHandler.Execute(command);
            }
        }
Example #15
0
        public static object Resolve(this IComponentContext componentContext, Type instanceType)
        {
            if (!componentContext.TryResolve(instanceType, out var instance))
            {
                ContextException.ResolveErr(instanceType);
            }

            return(instance);
        }
Example #16
0
        public IValidator?GetValidator(Type type)
        {
            var genericType = typeof(IValidator <>).MakeGenericType(type);

            if (container.TryResolve(genericType, out object validator))
            {
                return((IValidator)validator);
            }
            return(null);
        }
Example #17
0
        public override IValidator CreateInstance(Type validatorType)
        {
            if (_context.TryResolve(validatorType, out object instance))
            {
                var validator = instance as IValidator;
                return(validator);
            }

            return(null);
        }
Example #18
0
            public MediatorPlan(Type handlerTypeTemplate, string handlerMethodName, Type messageType, IComponentContext componentContext)
            {
                var handlerType = handlerTypeTemplate.MakeGenericType(messageType, typeof(TResponse));

                _handleMethod = GetHandlerMethod(handlerType, handlerMethodName, messageType);

                if (!componentContext.TryResolve(handlerType, out _handlerInstance))
                {
                    throw new InvalidOperationException(string.Format("Failed to find a handler for {0} => {1}", messageType.Name, typeof(TResponse).Name));
                }
            }
        private static void RegisterLogger(IComponentContext context, PostgreSQLOptions options)
        {
            ILogger logger = null;

            if (context.TryResolve <ILogger>(out logger))
            {
                NpgsqlLogManager.IsParameterLoggingEnabled = true;
                NpgsqlLogManager.Provider = new PostgreSQLLoggingProvider(logger, options.LogLevel);
            }
            loggerRegistered = true;
        }
Example #20
0
        public object CreateValidator <TModel>()
        {
            IValidator <TModel> validator;

            if (_context.TryResolve(out validator))
            {
                return(validator);
            }

            return(null);
        }
Example #21
0
        public T TryResolve <T>()
        {
            T result;

            if (_componentContext.TryResolve(out result))
            {
                return(result);
            }

            return(default(T));
        }
        private IValidator GetValidator <T>()
        {
            Type validatorType = typeof(IValidator <>).MakeGenericType(typeof(T));

            if (_container.TryResolve(validatorType, out object validator))
            {
                return((IValidator)validator);
            }

            return(null);
        }
Example #23
0
 private static bool TryResolveAtScope(IComponentContext scope, string key, Type serviceType, out object value)
 {
     if (scope != null)
     {
         return(key == null
             ? scope.TryResolve(serviceType, out value)
             : scope.TryResolveKeyed(key, serviceType, out value));
     }
     value = null;
     return(false);
 }
        public IExtendedXmlSerializerConfig GetConfiguration(Type type)
        {
            var    genericTyep = typeof(ExtendedXmlSerializerConfig <>).MakeGenericType(type);
            object result;

            if (_context.TryResolve(genericTyep, out result))
            {
                return(result as IExtendedXmlSerializerConfig);
            }
            return(null);
        }
Example #25
0
        public static void Register(this IComponentContext context, Action <ContainerBuilder> action)
        {
            object register;

            if (!context.TryResolve(typeof(IAutofacRegister), out register))
            {
                throw new NotSupportedException();
            }

            ((IAutofacRegister)register).Register(action);
        }
Example #26
0
        public void TryResolve()
        {
            ChromeOptions chromeOptions = null;

            if (componentContext.TryResolve(out chromeOptions))
            {
                DriverOptions = chromeOptions;
            }
            FirefoxOptions firefoxOptions = null;

            if (componentContext.TryResolve(out firefoxOptions))
            {
                DriverOptions = firefoxOptions;
            }
            BrowserScripts scripts = null;

            if (componentContext.TryResolve(out scripts))
            {
                Scripts = scripts;
            }
        }
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces();

            builder.Register <ServiceFactory>(ctx =>
            {
                IComponentContext componentContext = ctx.Resolve <IComponentContext>();
                return(t => { object o; return componentContext.TryResolve(t, out o) ? o : null; });
            });
        }
        public IValidator GetValidator(Type type)
        {
            var genericType = typeof(IValidator <>).MakeGenericType(type);

            // Search if IValidator<> exists in Autofac container. If it exists then resolve it. Otherwise, return null.
            if (_container.TryResolve(genericType, out var validator))
            {
                return((IValidator)validator);
            }

            return(null);
        }
        static void OnCodeSwitchActivation(IComponentContext context, IObservable <ICodeSwitchEvaluated> observable)
        {
            IEnumerable <IObserver <ICodeSwitchEvaluated> > observers;

            if (context.TryResolve(out observers))
            {
                foreach (var observer in observers)
                {
                    observable.Subscribe(observer);
                }
            }
        }
Example #30
0
        /// <summary>
        /// Publish the event
        /// </summary>
        /// <typeparam name="TEvent"></typeparam>
        /// <param name="event"></param>
        public void Send <TEvent>(TEvent @event) where TEvent : IEvent
        {
            IEnumerable <IEventHandler <TEvent> > eventHandlers = null;

            if (_componentContext.TryResolve <IEnumerable <IEventHandler <TEvent> > >(out eventHandlers))
            {
                foreach (IEventHandler <TEvent> eventHandler in eventHandlers)
                {
                    eventHandler.Handle(@event);
                }
            }
        }
Example #31
0
 private static object GetService(IComponentContext context, Type serviceType)
 {
     object service;
       context.TryResolve(serviceType, out service);
       return service;
 }