Ejemplo n.º 1
0
        private object InternalLocate(IExportLocatorScope scope, IDisposalScope disposalScope, Type type, ActivationStrategyFilter consider, object key, IInjectionContext injectionContext, bool allowNull, bool isDynamic)
        {
            if (type == typeof(ILocatorService) || type == typeof(IExportLocatorScope))
            {
                return(scope);
            }

            if (isDynamic)
            {
                if (type.IsArray)
                {
                    return(DynamicArray(scope, disposalScope, type, consider, injectionContext));
                }

                if (type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                {
                    return(DynamicIEnumerable(scope, disposalScope, type, consider, injectionContext));
                }
            }

            var compiledDelegate = InternalFieldStorage.ActivationStrategyCompiler.FindDelegate(this, type, consider, key, injectionContext, InternalFieldStorage.MissingExportStrategyProviders != ImmutableLinkedList <IMissingExportStrategyProvider> .Empty);

            if (compiledDelegate != null)
            {
                if (key == null && consider == null)
                {
                    compiledDelegate = AddObjectFactory(type, compiledDelegate);
                }

                return(compiledDelegate(scope, disposalScope ?? (DisposalScope ?? DisposalScopeProvider.ProvideDisposalScope(scope)), injectionContext));
            }

            if (Parent != null)
            {
                var injectionScopeParent = (IInjectionScope)Parent;

                return(injectionScopeParent.LocateFromChildScope(scope, disposalScope, type, injectionContext, consider, key, allowNull, isDynamic));
            }

            if (type == typeof(IInjectionScope) &&
                ScopeConfiguration.Behaviors.AllowInjectionScopeLocation)
            {
                return(scope);
            }

            var value = ScopeConfiguration.Implementation.Locate <IInjectionContextValueProvider>()
                        .GetValueFromInjectionContext(scope, type, null, injectionContext, !allowNull);

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

            if (!allowNull)
            {
                throw new LocateException(new StaticInjectionContext(type));
            }

            return(null);
        }
Ejemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="disposalScope"></param>
        /// <param name="exportName"></param>
        /// <param name="extraData"></param>
        /// <param name="consider"></param>
        /// <returns></returns>
        List <object> IInjectionScope.InternalLocateAllByName(IExportLocatorScope scope, IDisposalScope disposalScope, string exportName, object extraData, ActivationStrategyFilter consider)
        {
            var context = CreateContext(extraData);

            var returnList = new List <object>();

            var collection = StrategyCollectionContainer.GetActivationStrategyCollectionByName(exportName);

            foreach (var strategy in collection.GetStrategies())
            {
                if (consider == null || consider(strategy))
                {
                    var activation = strategy.GetActivationStrategyDelegate(this,
                                                                            InternalFieldStorage.ActivationStrategyCompiler, typeof(object));

                    returnList.Add(activation(scope, disposalScope, context.Clone()));
                }
            }

            var injectionScopeParent = Parent as IInjectionScope;

            if (injectionScopeParent != null)
            {
                returnList.AddRange(injectionScopeParent.InternalLocateAllByName(scope, disposalScope, exportName, context, consider));
            }

            return(returnList);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="scope"></param>
 /// <param name="context"></param>
 /// <param name="activationDelegate"></param>
 /// <param name="scopeName"></param>
 public Scoped(IExportLocatorScope scope, IInjectionContext context, ActivationStrategyDelegate activationDelegate, string scopeName = null)
 {
     _scope              = scope;
     _context            = context;
     _activationDelegate = activationDelegate;
     _scopeName          = scopeName;
 }
        public TableLessonViewPageModel(
            TableLessonViewToken token, LocalDbContext db, IExportLocatorScope scope, TabPageHost host
            )
        {
            _db        = db;
            _scope     = scope;
            _host      = host;
            this.Items = new CollectionViewSource {
                Source = _items
            };
            this.Columns.Add(BuildMissedLessonsColumn());
            this.WhenActivated(c => {
                this.WhenAnyValue(model => model.FilterText)
                .Throttle(TimeSpan.FromMilliseconds(300))
                .ObserveOnDispatcher(DispatcherPriority.Background)
                .Subscribe(_ => {
                    if (string.IsNullOrWhiteSpace(this.FilterText))
                    {
                        this.Items.View.Filter = null;
                        return;
                    }

                    this.Items.View.Filter =
                        o => o is StudentLessonViewModel item &&
                        item.FullName.ToUpper().Contains(this.FilterText.ToUpper());
                }).DisposeWith(c);
            });

            Init(token.Lesson);
        }
Ejemplo n.º 5
0
            protected virtual object LocateFromChildContainer(IInjectionContextValueProvider valueProvider,
                                                              IExportLocatorScope scope,
                                                              StaticInjectionContext staticContext,
                                                              Type type,
                                                              object key,
                                                              IInjectionContext context,
                                                              object defaultValue,
                                                              bool useDefault,
                                                              bool isRequired)
            {
                var value = valueProvider.GetValueFromInjectionContext(scope, type, key, context, false);

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

                if (scope.TryLocate(type, out value, context, withKey: key))
                {
                    return(value);
                }

                if (useDefault)
                {
                    return(defaultValue);
                }

                if (isRequired)
                {
                    throw new LocateException(staticContext);
                }

                return(null);
            }
Ejemplo n.º 6
0
 public ScriptDependencyResolver(IEnumerable <Type> typeUniverse, IExportLocatorScope locatorService,
                                 IDialog dialog)
 {
     this.typeUniverse   = typeUniverse;
     this.locatorService = locatorService;
     this.dialog         = dialog;
 }
Ejemplo n.º 7
0
            /// <summary>
            /// Method that is called each time a delegate needs to be created
            /// </summary>
            /// <param name="scope"></param>
            /// <param name="disposalScope"></param>
            /// <param name="context"></param>
            /// <returns></returns>
            public TDelegate CreateDelegate(IExportLocatorScope scope, IDisposalScope disposalScope,
                                            IInjectionContext context)
            {
                var funcClass = new FuncClass(scope, disposalScope, context, _action, _injectionContextCreator, _arg1Id, _arg2Id, _arg3Id, _arg4Id, _arg5Id);

                return((TDelegate)((object)_funcMethodInfo.CreateDelegate(typeof(TDelegate), funcClass)));
            }
Ejemplo n.º 8
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="scope"></param>
        /// <param name="context"></param>
        /// <param name="parameterName"></param>
        /// <returns></returns>
        public virtual bool DynamicCanLocate <T>(IExportLocatorScope scope, IInjectionContext context, string parameterName)
        {
            var value = context.GetExtraData(parameterName);

            if (value is T)
            {
                return(true);
            }

            value = context.GetValueByType(typeof(T));

            if (value is T)
            {
                return(true);
            }

            var currentScope = scope;

            while (currentScope != null)
            {
                if (currentScope.GetExtraData(parameterName) != null ||
                    currentScope.Values.Any(o => o is T))
                {
                    return(true);
                }

                currentScope = currentScope.Parent;
            }

            return(scope.GetInjectionScope().CanLocate(typeof(T)));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="includeParent"></param>
        /// <param name="consider"></param>
        /// <returns></returns>
        public static string WhatDoIHave(this IExportLocatorScope scope, bool includeParent = true,
                                         ActivationStrategyFilter consider = null)
        {
            var builder = new StringBuilder();

            var locator = scope.GetInjectionScope();

            builder.AppendLine(new string('-', 80));

            builder.AppendFormat("Exports for scope '{0}' with id {1}{2}",
                                 locator.ScopeName,
                                 locator.ScopeId,
                                 Environment.NewLine);

            foreach (var exportStrategy in locator.StrategyCollectionContainer.GetAllStrategies())
            {
                ProcessExportStrategy(builder, exportStrategy);
            }

            if (includeParent && locator.Parent != null)
            {
                builder.Append(WhatDoIHave(scope.Parent, true, consider));
            }

            return(builder.ToString());
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="scope"></param>
 /// <param name="disposalScope"></param>
 /// <param name="context"></param>
 /// <param name="action"></param>
 /// <param name="injectionContextCreator"></param>
 public FuncClass(IExportLocatorScope scope, IDisposalScope disposalScope, IInjectionContext context, ActivationStrategyDelegate action, IInjectionContextCreator injectionContextCreator)
 {
     _scope                   = scope;
     _disposalScope           = disposalScope;
     _context                 = context;
     _action                  = action;
     _injectionContextCreator = injectionContextCreator;
 }
            /// <summary>
            /// Default constructor
            /// </summary>
            /// <param name="injectionScope"></param>
            public GraceServiceScope(IExportLocatorScope injectionScope)
            {
                _injectionScope = injectionScope;
#if NETSTANDARD1_0
                ServiceProvider = new GraceServiceProvider(injectionScope);
#else
                ServiceProvider = injectionScope;
#endif
            }
Ejemplo n.º 12
0
        private static Func <Type, object> CreateFunc(IExportLocatorScope scope, IInjectionContext context)
        {
            return(type =>
            {
                var clone = context.Clone();

                return scope.Locate(type, clone);
            });
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="parent">parent scope</param>
        /// <param name="name">name of scope</param>
        /// <param name="delegateCache">delegate cache</param>
        protected BaseExportLocatorScope(IExportLocatorScope parent,
                                      string name,
                                      ActivationStrategyDelegateCache delegateCache)
        {
            Parent = parent;
            ScopeName = name ?? "";

            DelegateCache = delegateCache;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Get the parent injection scope for this export locator scope
        /// </summary>
        /// <param name="scope">export locator scope</param>
        /// <returns>parent injection scope</returns>
        public static IInjectionScope GetInjectionScope(this IExportLocatorScope scope)
        {
            while (!(scope is IInjectionScope))
            {
                scope = scope.Parent;
            }

            return((IInjectionScope)scope);
        }
Ejemplo n.º 15
0
 public HomeController(IExportLocatorScope locator, IAccountRepository accountRepo, IAccountService accountSvc, IUserService userSvc)
 {
     this.locator = locator;
     //获取简单注册实例
     this.accountRepo = accountRepo;
     this.accountSvc  = accountSvc;
     //获取指定键值的实例
     this.userRepo = this.locator.Locate <IUserRepository>(withKey: "A");
     this.userSvc  = userSvc;
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Create GraceOptional instance.
 /// </summary>
 /// <param name="scope"></param>
 /// <param name="disposalScope"></param>
 /// <param name="injectionContext"></param>
 /// <returns></returns>
 public GraceOptional <TResult> CreateOptional(
     IExportLocatorScope scope,
     IDisposalScope disposalScope,
     IInjectionContext injectionContext)
 {
     return(new GraceOptional <TResult>(scope, qualifier, () =>
     {
         return (TResult)_delegate(scope, disposalScope, injectionContext);
     }));
 }
Ejemplo n.º 17
0
        private object DynamicArray(IExportLocatorScope scope, IDisposalScope disposalScope, Type type, ActivationStrategyFilter consider, IInjectionContext injectionContext)
        {
            if (InternalFieldStorage.DynamicArrayLocator == null)
            {
                Interlocked.CompareExchange(ref InternalFieldStorage.DynamicArrayLocator,
                                            ScopeConfiguration.Implementation.Locate <IDynamicArrayLocator>(), null);
            }

            return(InternalFieldStorage.DynamicArrayLocator.Locate(this, scope, disposalScope, type, consider, injectionContext));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="parent">parent scope</param>
        /// <param name="name">name of scope</param>
        /// <param name="activationDelegates">activation delegates</param>
        protected BaseExportLocatorScope(IExportLocatorScope parent,
                                         string name,
                                         ImmutableHashTree <Type, ActivationStrategyDelegate>[] activationDelegates)
        {
            Parent         = parent;
            ScopeIdAndName = new ScopeIdAndNameClass(name);

            ActivationDelegates = activationDelegates;
            ArrayLengthMinusOne = activationDelegates.Length - 1;
        }
Ejemplo n.º 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="childScope"></param>
        /// <param name="disposalScope"></param>
        /// <param name="name"></param>
        /// <param name="extraData"></param>
        /// <param name="consider"></param>
        /// <param name="allowNull"></param>
        /// <returns></returns>
        object IInjectionScope.LocateByNameFromChildScope(IExportLocatorScope childScope, IDisposalScope disposalScope,
                                                          string name,
                                                          object extraData, ActivationStrategyFilter consider, bool allowNull)
        {
            var collection = StrategyCollectionContainer.GetActivationStrategyCollectionByName(name);

            ICompiledExportStrategy strategy = null;

            if (collection != null)
            {
                if (consider != null)
                {
                    var context = new StaticInjectionContext(typeof(object));

                    strategy =
                        collection.GetStrategies()
                        .FirstOrDefault(
                            s => (!s.HasConditions || s.Conditions.All(con => con.MeetsCondition(s, context))) && consider(s));
                }
                else
                {
                    strategy = collection.GetPrimary();

                    if (strategy == null)
                    {
                        var context = new StaticInjectionContext(typeof(object));

                        strategy = collection.GetStrategies()
                                   .FirstOrDefault(
                            s => !s.HasConditions || s.Conditions.All(con => con.MeetsCondition(s, context)));
                    }
                }
            }

            if (strategy != null)
            {
                var strategyDelegate =
                    strategy.GetActivationStrategyDelegate(this, InternalFieldStorage.ActivationStrategyCompiler, typeof(object));

                return(strategyDelegate(childScope, disposalScope, CreateContext(extraData)));
            }

            if (Parent != null)
            {
                return(((IInjectionScope)Parent).LocateByNameFromChildScope(childScope, disposalScope, name, extraData,
                                                                            consider, allowNull));
            }

            if (!allowNull)
            {
                throw new LocateException(new StaticInjectionContext(typeof(object)));
            }

            return(null);
        }
            /// <summary>
            /// Method that creates one arg Func
            /// </summary>
            /// <param name="scope"></param>
            /// <param name="disposalScope"></param>
            /// <param name="context"></param>
            /// <returns></returns>
            public Func <TArg1, TResult> CreateFunc(IExportLocatorScope scope, IDisposalScope disposalScope, IInjectionContext context)
            {
                return(arg1 =>
                {
                    var newContext = context?.Clone() ?? _injectionContextCreator.CreateContext(null);

                    newContext.SetExtraData(_arg1Id, arg1);

                    return (TResult)_action(scope, disposalScope, newContext);
                });
            }
Ejemplo n.º 21
0
        public virtual object PreBuildUp(StaticInjectionContext staticContext, IExportLocatorScope scope,
                                         IInjectionContext injectionContext)
        {
            var timer = new Stopwatch();

            injectionContext.SetExtraData(staticContext.TargetInfo.UniqueId, timer);

            timer.Start();

            return(null);
        }
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="scope"></param>
 /// <param name="disposalScope"></param>
 /// <param name="context"></param>
 /// <param name="action"></param>
 /// <param name="injectionContextCreator"></param>
 /// <param name="arg1Id"></param>
 /// <param name="arg2Id"></param>
 /// <param name="arg3Id"></param>
 /// <param name="arg4Id"></param>
 public FuncClass(IExportLocatorScope scope, IDisposalScope disposalScope, IInjectionContext context, ActivationStrategyDelegate action, IInjectionContextCreator injectionContextCreator, string arg1Id, string arg2Id, string arg3Id, string arg4Id)
 {
     _scope                   = scope;
     _disposalScope           = disposalScope;
     _context                 = context;
     _action                  = action;
     _injectionContextCreator = injectionContextCreator;
     _arg1Id                  = arg1Id;
     _arg2Id                  = arg2Id;
     _arg3Id                  = arg3Id;
     _arg4Id                  = arg4Id;
 }
Ejemplo n.º 23
0
            OneDependency DoSomethingToEnrich(OneDependency instance, IExportLocatorScope scope, IInjectionContext injContext)
            {
                var staticContext = (StaticInjectionContext)injContext.GetExtraData("staticcontext");

                //There I would want to somehow know that we are modifying an instance being injected into a constructor parameter
                //decorated with [AnAttribute], but obviously ctx does not have any information about the original request
                if (staticContext.TargetInfo.InjectionTargetAttributes.OfType <AnAttributeAttribute>().Any())
                {
                    instance.Value = "Success";
                }
                return(instance);
            }
Ejemplo n.º 24
0
        public void Configure(IExportLocatorScope container)
        {
            container.Configure(c => c
                                .Export <NotifierPropertyActivator>()
                                .As <IActivator>()
                                .WhenInjectedInto <NotifierObject>()
                                .When(t => t.Context.TargetMemberInfo is PropertyInfo)
                                .WithPriority(1)
                                );

            container.Configure(e => e.Export(typeof(Notifier <>)).GenericAsTarget().As <INotifier>());
        }
Ejemplo n.º 25
0
            /// <summary>
            /// Create lazy instance
            /// </summary>
            /// <param name="scope"></param>
            /// <param name="disposalScope"></param>
            /// <param name="injectionContext"></param>
            /// <returns></returns>
            public Lazy <TResult> CreateLazy(IExportLocatorScope scope, IDisposalScope disposalScope,
                                             IInjectionContext injectionContext)
            {
                return(new Lazy <TResult>(() =>
                {
                    if (_delegate == null)
                    {
                        _delegate = CompileDelegate();
                    }

                    return (TResult)_delegate(scope, disposalScope, injectionContext);
                }));
            }
Ejemplo n.º 26
0
        public void RegisterEntities(IExportLocatorScope container)
        {
            _container = container;
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypesSafe().Where(t => t.IsClass && !t.IsAbstract && typeof(IEntity).IsAssignableFrom(t)))
                {
                    Entities.Add(type);
                }
            }
        }
Ejemplo n.º 27
0
            /// <summary>
            /// Create lazy instance
            /// </summary>
            /// <param name="scope"></param>
            /// <param name="disposalScope"></param>
            /// <param name="injectionContext"></param>
            /// <returns></returns>
            public Lazy <TResult, IActivationStrategyMetadata> CreateLazy(IExportLocatorScope scope, IDisposalScope disposalScope,
                                                                          IInjectionContext injectionContext)
            {
                return(new Lazy <TResult, IActivationStrategyMetadata>(() =>
                {
                    if (_delegate == null)
                    {
                        _delegate = CompileDelegate();
                    }

                    return (TResult)_delegate(scope, disposalScope, injectionContext);
                }, _metadata));
            }
Ejemplo n.º 28
0
        /// <summary>
        /// Execute delegate by injecting parameters then executing
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="context"></param>
        /// <param name="injectionContext"></param>
        /// <param name="delegate"></param>
        /// <returns></returns>
        public static object InjectAndExecuteDelegate(IExportLocatorScope scope, StaticInjectionContext context,
                                                      IInjectionContext injectionContext, Delegate @delegate)
        {
            var executeFunc = _executeDelegateWithInjections.GetValueOrDefault(@delegate.GetType());

            if (executeFunc == null)
            {
                executeFunc = CreateExecuteDelegate(@delegate);

                _executeDelegateWithInjections = _executeDelegateWithInjections.Add(@delegate.GetType(), executeFunc);
            }

            return(executeFunc(scope, context, injectionContext, @delegate));
        }
Ejemplo n.º 29
0
        public async Task Invoke(
            HttpContext httpContext,
            IExportLocatorScope locatorScope,
            Lazy <ITenantContainerBuilder <TTenant> > builder
            )
        {
            var tenant = _tenantResolver.Resolve(httpContext);

            using (var scope = await builder.Value.BuildAsync(tenant))
            {
                httpContext.RequestServices = scope.Locate <IServiceProvider>();
                await _next(httpContext);
            }
        }
            /// <summary>
            /// Method that creates new Func with 4 args
            /// </summary>
            /// <param name="scope"></param>
            /// <param name="disposalScope"></param>
            /// <param name="context"></param>
            /// <returns></returns>
            public Func <T1, T2, T3, T4, TResult> CreateFunc(IExportLocatorScope scope, IDisposalScope disposalScope,
                                                             IInjectionContext context)
            {
                return((arg1, arg2, arg3, arg4) =>
                {
                    var newContext = context?.Clone() ?? _injectionContextCreator.CreateContext(null);

                    newContext.SetExtraData(_t1Id, arg1);
                    newContext.SetExtraData(_t2Id, arg2);
                    newContext.SetExtraData(_t3Id, arg3);
                    newContext.SetExtraData(_t4Id, arg4);

                    return (TResult)_action(scope, disposalScope, newContext);
                });
            }