예제 #1
0
 public void Extract(TypeDefinition targetDependency,
     ModuleDefinition hostModule,
     IDependencyScope scope)
 {
     // Step 7: Replace all type instances of the target dependency with the new interface
     _swappers.ForEach(swapper => swapper.SwapDependencies(scope, targetDependency));
 }
예제 #2
0
        public static IDependencyScope GetSuperscribeDependencyScope(this HttpRequestMessage request, IDependencyScope existingScope)
        {
            var routeWalker = request.GetOwinContext().Environment[Constants.SuperscribeRouteWalkerEnvironmentKey] as IRouteWalker;
            var routeDataProvider = request.GetOwinContext().Environment[Constants.SuperscribeRouteDataProviderEnvironmentKey] as IRouteDataProvider;

            return new SuperscribeDependencyScopeAdapter(existingScope, routeWalker, routeDataProvider);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AutofacWebApiDependencyResolver"/> class.
        /// </summary>
        /// <param name="container">The container that nested lifetime scopes will be create from.</param>
        public AutofacWebApiDependencyResolver(ILifetimeScope container)
        {
            if (container == null) throw new ArgumentNullException("container");

            _container = container;
            _rootDependencyScope = new AutofacWebApiDependencyScope(container);
        }
		private static Func<IMessage, Task<object>> GenerateNext(
			BusSettings busSettings,
			IDependencyScope dependencyScope,
			IReadOnlyCollection<Type> pipelineHandlerTypes,
			IEnumerable<Type> leftHandlerTypes
			)
		{
			return (async message => {

				if (message == null) {
					throw new NullMessageTypeException();
				}

				if (!pipelineHandlerTypes.Any()) {
					return await RunLeafHandlers(busSettings, dependencyScope, leftHandlerTypes, message);
				}

				var head = pipelineHandlerTypes.First();
				var nextHandler = (IPipelineHandler)dependencyScope.GetService(head);

				var tail = pipelineHandlerTypes.Skip(1).ToList();
				var nextFunction = GenerateNext(busSettings, dependencyScope, tail, leftHandlerTypes);

				return await nextHandler.Handle(nextFunction, message);
			});
		}
 public DependencyScopeExtensionsTests()
 {
     _resolverMock = new Mock<IDependencyScope>();
     _resolver = _resolverMock.Object;
     _service1 = new Service();
     _service2 = new Service();
 }
 public IDependencyScope BeginScope()
 {
     FluentWindsor.WaitUntilComplete.WaitOne();
     if (scope == null)
         scope = new FluentWindsorDependencyScope();
     return scope;
 }
예제 #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RequestDependencyScope"/> class.
        /// </summary>
        /// <param name="currentScope">The current <see cref="IDependencyScope">dependency scope</see>.</param>
        /// <param name="request">The current <see cref="HttpRequestMessage">request</see>.</param>
        public RequestDependencyScope( IDependencyScope currentScope, HttpRequestMessage request )
        {
            Arg.NotNull( currentScope, nameof( currentScope ) );
            Arg.NotNull( request, nameof( request ) );

            scope = currentScope;
            this.request = request;
        }
        public void SwapDependencies(IDependencyScope scope, TypeDefinition targetDependency)
        {
            var targetMethods = scope.Methods;
            var targetConstructors = scope.Constructors;

            targetMethods.ForEach(method => SwapParameterTypes(method, targetDependency, _interfaceType, _modifiedMethods));
            targetConstructors.ForEach(method => SwapParameterTypes(method, targetDependency, _interfaceType, _modifiedConstructors));
        }
 public SuperscribeDependencyScopeAdapter(
     IDependencyScope requestContainer,
     IRouteWalker routeWalker,
     IRouteDataProvider routeDataProvider)
 {
     this._requestContainer = requestContainer;
     this.routeWalker = routeWalker;
     this.routeDataProvider = new WebApiRouteDataProviderAdapter(routeDataProvider);
 }
예제 #10
0
 public CreateInterfaceType(IMethodFilter methodFilter, 
                            IMethodBuilder methodBuilder, 
                            IDependencyScope scope, 
                            TypeDefinition targetDependency,
                            ModuleDefinition module)
 {
     _methodFilter = methodFilter;
     _methodBuilder = methodBuilder;
     _scope = scope;
     _targetDependency = targetDependency;
     _module = module;
 }
예제 #11
0
        public WindsorDependencyScope(IDependencyScope scope, Action<object> releaseAction)
        {
            if (scope == null)
                throw new ArgumentNullException("scope");

            if (releaseAction == null)
                throw new ArgumentNullException("releaseAction");

            _scope = scope;
            _releaseActions = releaseAction;
            _objectInstances = new List<object>();
        }
예제 #12
0
        public void SwapDependencies(IDependencyScope scope, TypeDefinition targetDependency)
        {
            var fields = scope.Fields;
            foreach (var field in fields)
            {
                var fieldType = field.FieldType;
                if (fieldType != targetDependency)
                    continue;

                field.FieldType = _interfaceType;
            }
        }
        /// <summary>
        /// Gets an <see cref="IWebHookReceiverConfig"/> implementation registered with the Dependency Injection engine
        /// or a default implementation if none is registered.
        /// </summary>
        /// <param name="services">The <see cref="IDependencyScope"/> implementation.</param>
        /// <returns>The registered <see cref="IWebHookReceiverManager"/> instance or a default implementation if none are registered.</returns>
        public static IWebHookReceiverConfig GetReceiverConfig(this IDependencyScope services)
        {
            IWebHookReceiverConfig receiverConfig = services.GetService <IWebHookReceiverConfig>();

            if (receiverConfig == null)
            {
                SettingsDictionary settings = services.GetSettings();
                ILogger            logger   = services.GetLogger();
                receiverConfig = ReceiverServices.GetReceiverConfig(settings, logger);
            }
            return(receiverConfig);
        }
        /// <summary>
        /// Gets an <see cref="IWebHookReceiverManager"/> implementation registered with the Dependency Injection engine
        /// or a default implementation if none is registered.
        /// </summary>
        /// <param name="services">The <see cref="IDependencyScope"/> implementation.</param>
        /// <returns>The registered <see cref="IWebHookReceiverManager"/> instance or a default implementation if none are registered.</returns>
        public static IWebHookReceiverManager GetReceiverManager(this IDependencyScope services)
        {
            IWebHookReceiverManager receiverManager = services.GetService <IWebHookReceiverManager>();

            if (receiverManager == null)
            {
                IEnumerable <IWebHookReceiver> receivers = services.GetReceivers();
                ILogger logger = services.GetLogger();
                receiverManager = ReceiverServices.GetReceiverManager(receivers, logger);
            }
            return(receiverManager);
        }
예제 #15
0
        /// <summary>
        /// Provides a <see cref="IDependencyScope"/> for the request.
        /// </summary>
        /// <param name="useDeepestRequest">Indicate whether to use the deepest request to locate the <see cref="IDependencyScope"/>.</param>
        /// <returns>A <see cref="IDependencyScope"/>.</returns>
        public IDependencyScope GetDependencyScope(bool useDeepestRequest)
        {
            HandlerRequest request = this.GetRootRequest(useDeepestRequest);

            if (request.dependencyScope == null)
            {
                IDependencyScope scope = this.Configuration.DependencyResolver.BeginScope();
                request.RegisterForDispose(scope);
                request.dependencyScope = scope;
            }

            return(request.dependencyScope);
        }
예제 #16
0
            protected override object ResolveInstance(Type contract, IDependencyScope scope)
            {
                var array = new T[_dependencies.Length];

                for (var index = 0; index < _dependencies.Length; index++)
                {
                    var dependency = _dependencies[index];
                    var instance   = dependency.GetInstance(_elementType, scope);
                    array[index] = (T)instance;
                }

                return(array);
            }
예제 #17
0
        public void SwapDependencies(IDependencyScope scope, TypeDefinition targetDependency)
        {
            foreach (var method in scope.Methods)
            {
                var returnType = method.ReturnType.ReturnType;
                if (returnType != targetDependency)
                {
                    continue;
                }

                method.ReturnType = new MethodReturnType(_interfaceType);
            }
        }
예제 #18
0
        public static IWebHookManager GetManager(this IDependencyScope services)
        {
            IWebHookManager manager = services.GetService <IWebHookManager>();

            if (manager == null)
            {
                IWebHookStore  store  = services.GetStore();
                IWebHookSender sender = services.GetSender();
                ILogger        logger = services.GetLogger();
                manager = CustomServices.GetManager(store, sender, logger);
            }
            return(manager);
        }
        public void BeginScope_should_return_the_dependency_resolver_itself(
            SimpleInjectorDependencyResolver dependencyResolver,
            IDependencyScope dependencyScope)
        {
            "Given a SimpleInjectorDependencyResolver"
            .Given(() => dependencyResolver = new SimpleInjectorDependencyResolver(new Container()));

            "When BeginScope is called"
            .When(() => dependencyScope = dependencyResolver.BeginScope());

            "Then the dependency scope returned should be the dependency resolver itself"
            .Then(() => dependencyScope.Should().BeSameAs(dependencyResolver));
        }
예제 #20
0
 /// <summary>
 /// Performs shutdown operations for the service.
 /// </summary>
 /// <param name="dependencyScope">
 /// A scope that is used to resolve service dependencies.
 /// </param>
 /// <param name="applicationConfiguration">
 /// Configuration information for the service application.
 /// </param>
 protected override void OnExecutionStopping(IDependencyScope dependencyScope, IConfiguration applicationConfiguration)
 {
     try
     {
         var mediator = dependencyScope.Resolve <ICommandMediator>();
         var applicationStoppedMessage = new ApplicationStoppingMessage(ServiceName);
         mediator.Process(applicationStoppedMessage);
         Thread.Sleep(3200);
     }
     finally
     {
         base.OnExecutionStopping(dependencyScope, applicationConfiguration);
     }
 }
예제 #21
0
        public static IWebHookRegistrationsManager GetRegistrationsManager(this IDependencyScope services)
        {
            IWebHookRegistrationsManager registrationsManager = services.GetService <IWebHookRegistrationsManager>();

            if (registrationsManager == null)
            {
                IWebHookManager       manager       = services.GetManager();
                IWebHookStore         store         = services.GetStore();
                IWebHookFilterManager filterManager = services.GetFilterManager();
                IWebHookUser          userManager   = services.GetUser();
                registrationsManager = CustomServices.GetRegistrationsManager(manager, store, filterManager, userManager);
            }
            return(registrationsManager);
        }
예제 #22
0
 public async override Task Invoke(IOwinContext context)
 {
     using (IDependencyScope scope = Resolver.BeginScope())
     {
         context.Set <IDependencyScope>(scope);
         context.Set <ManahostManagerDAL>((ManahostManagerDAL)scope.GetService(typeof(ManahostManagerDAL)));
         var scopeUnity = scope as UnityResolver;
         scopeUnity.RegisterInstance(new UnityRegisterScope()
         {
             Scope = scope
         });
         await Next.Invoke(context);
     }
 }
예제 #23
0
        public override object GetInstance(Type contract, IDependencyScope scope)
        {
            if (_instances.TryGetValue(scope, out var existsInstance))
            {
                return(existsInstance);
            }

            var instance = Resolve(contract, scope);

            _instances.Add(scope, instance);
            scope.Destroy += OnScopeDestroy;

            return(instance);
        }
예제 #24
0
        public async Task <HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func <Task <HttpResponseMessage> > continuation)
        {
            IDependencyScope dependencyScope = actionContext.Request.GetDependencyScope();
            var filters = (IEnumerable <IAuthorizationFilter>)dependencyScope.GetServices(typeof(IAuthorizationFilter));

            filters = filters.Reverse();

            Func <Task <HttpResponseMessage> > result = filters.Aggregate(continuation, (currentContinuation, filter) =>
            {
                return(() => filter.ExecuteAuthorizationFilterAsync(actionContext, cancellationToken, currentContinuation));
            });

            return(await result());
        }
예제 #25
0
        /// <summary>
        /// Gets the set of <see cref="IWebHookHandler"/> instances registered with the Dependency Injection engine
        /// or an empty collection if none are registered.
        /// </summary>
        /// <param name="services">The <see cref="IDependencyScope"/> implementation.</param>
        /// <returns>An <see cref="IEnumerable{T}"/> containing the registered instances.</returns>
        public static IEnumerable <IWebHookHandler> GetHandlers(this IDependencyScope services)
        {
            IEnumerable <IWebHookHandler> handlers = services.GetServices <IWebHookHandler>();

            if (handlers == null || !handlers.Any())
            {
                handlers = ReceiverServices.GetHandlers();
            }

            // Sort handlers
            IWebHookHandlerSorter sorter = services.GetHandlerSorter();

            return(sorter.SortHandlers(handlers));
        }
        public static Task <HttpResponseMessage> InvokeAction(
            HttpRequestMessage request)
        {
            HttpController controller;

            HttpRequestContext context = request.GetRequestContext();

            if (context == null)
            {
                throw new InvalidOperationException("Cannot find request context");
            }

            HttpRoute         matchedRoute  = context.MatchedRoute;
            HttpConfiguration configuration = context.Configuration;

            #region Please modify the following code

            /*
             * A dependency scope will be generated for each request. And it will manage the
             * lifetime scopes for all items created during this request.
             */
            IDependencyScope scope = context.GetDependencyScope();
            #endregion

            try
            {
                controller = configuration.ControllerFactory.CreateController(
                    matchedRoute.ControllerName,
                    configuration.CachedControllerTypes,
                    scope);

                if (controller == null)
                {
                    return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)));
                }

                controller.Request = request;
            }
            catch (ArgumentException)
            {
                return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError)));
            }

            return(InvokeActionInternal(
                       new ActionDescriptor(
                           controller,
                           matchedRoute.ActionName,
                           matchedRoute.MethodConstraint)));
        }
예제 #27
0
        public static void SynchronizeDb(this IApplicationBuilder services, IDependencyScope scope)
        {
            var leagueSynchronizer = scope.Resolve <IEntitySynchronizer <League, JLeague> >();

            leagueSynchronizer.Synchronize("/competitions");

            ////var teamsSynchronizer = scope.Resolve<IEntitySynchronizer<Team, JTeam>>();
            ////teamsSynchronizer.Synchronize(("/teams"));

            ////var matchesSynchronizer = scope.Resolve<IEntitySynchronizer<Match, JMatch>>();
            ////matchesSynchronizer.Synchronize("/matches");

            ////var seasonsSynchronizer = scope.Resolve<IEntitySynchronizer<Season, JSeason>>();
            ////seasonsSynchronizer.Synchronize("/seasons");
        }
예제 #28
0
        public override bool IsValid(object value)
        {
            var dependencyResolver = (AutofacWebApiDependencyResolver)GlobalConfiguration.Configuration.DependencyResolver;

            using (IDependencyScope lifetimeScope = dependencyResolver.BeginScope())
            {
                INewsService newsService = (INewsService)(lifetimeScope.GetService(typeof(INewsService)));

                if (value != null && (value is string))
                {
                    return(!newsService.CheckUniqueTitle(value.ToString()));
                }
                return(false);
            }
        }
예제 #29
0
        public object Resolve(Type contract, IDependencyScope scope)
        {
            if (_resolveInProgress)
            {
                throw Error.CircularDependency(contract);
            }

            _resolveInProgress = true;

            var instance = ResolveInstance(contract, scope);

            _resolveInProgress = false;

            return(instance);
        }
예제 #30
0
 public Mediator(
     ICommandReceivePipe <IReceiveContext <ICommand> > commandReceivePipe,
     IEventReceivePipe <IReceiveContext <IEvent> > eventReceivePipe,
     IRequestReceivePipe <IReceiveContext <IRequest> > requestPipe,
     IPublishPipe <IPublishContext <IEvent> > publishPipe,
     IGlobalReceivePipe <IReceiveContext <IMessage> > globalPipe,
     IDependencyScope scope = null)
 {
     _commandReceivePipe = commandReceivePipe;
     _eventReceivePipe   = eventReceivePipe;
     _requestPipe        = requestPipe;
     _publishPipe        = publishPipe;
     _globalPipe         = globalPipe;
     _scope = scope;
 }
예제 #31
0
        public async override Task Invoke(IOwinContext context)
        {
            if (context.Authentication.User != null && !String.IsNullOrWhiteSpace(context.Authentication.User.Identity.Name) && context.Authentication.User.Identity.IsAuthenticated)
            {
                IDependencyScope  Scope       = context.Get <IDependencyScope>();
                ClientUserManager UserManager = Scope.GetService(typeof(ClientUserManager)) as ClientUserManager;
                var userClient = await UserManager.FindByEmailAsync(context.Authentication.User.Identity.Name);

                if (userClient.Locale != null && !string.IsNullOrEmpty(userClient.Locale))
                {
                    Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(userClient.Locale);
                }
            }
            await Next.Invoke(context);
        }
예제 #32
0
        /// <summary>
        /// Get <see cref="ICacheStrategy" /> from <see cref="IDependencyScope" />
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="invocation"></param>
        /// <param name="invocationContext"></param>
        /// <returns></returns>
        protected virtual ICacheStrategy GetCacheStrategy(IDependencyScope scope, _IInvocation invocation, IDictionary <string, object> invocationContext)
        {
            var strategy = CacheStrategyType != null?scope.GetService(CacheStrategyType) as ICacheStrategy : null;

            if (strategy == null)
            {
                var strategyProvider = scope.GetService(typeof(ICacheStrategyProvider)) as ICacheStrategyProvider ?? Global.CacheStrategyProvider;
                strategy = strategyProvider.GetStrategy(invocation, invocationContext);
            }
            if (strategy == null)
            {
                throw new Exception("Cannot find caching strategy for this request");
            }
            return(strategy);
        }
예제 #33
0
        public void SwapDependencies(IDependencyScope scope, TypeDefinition targetDependency)
        {
            var fields = scope.Fields;

            foreach (var field in fields)
            {
                var fieldType = field.FieldType;
                if (fieldType != targetDependency)
                {
                    continue;
                }

                field.FieldType = _interfaceType;
            }
        }
예제 #34
0
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true; // contains self

            _defaultScope.Dispose();
            _defaultScope = null !;

            _engine.Dispose();
            _engine = null !;
        }
예제 #35
0
        /// <summary>
        ///   Selects a handler to serve as the default generator of HTTP challenges.
        /// </summary>
        ///
        /// <param name="locator">The resolver to use for locating dependencies</param>
        ///
        /// <returns>The <see cref="OrderFulfillment.Api.Security.IAuthenticationHandler" /> to use as the deafult challenge generator, if one is available; otherwise, <c>null</c>.</returns>
        ///
        private static IAuthenticationHandler SelectDefaultChallengeHandler(IDependencyScope locator)
        {
            // If there was no dependency resolver then a handler cannot be selected.

            if (locator == null)
            {
                return(null);
            }

            // Select the strongest authentication handler to issue the default challenge.

            var handlerCandidates = (IEnumerable <IAuthenticationHandler>)locator.GetServices(typeof(IAuthenticationHandler));

            return(handlerCandidates?.Where(candidate => ((candidate.Enabled) && (candidate.CanGenerateChallenge))).OrderByDescending(candidate => candidate.Strength).FirstOrDefault());
        }
예제 #36
0
        private void OnScopeDestroy(IDependencyScope scope)
        {
            if (!_instances.TryGetValue(scope, out var instance))
            {
                return;
            }

            _instances.Remove(scope);
            scope.Destroy -= OnScopeDestroy;

            if (ReflectionUtils.IsDisposable(instance, out var disposable))
            {
                disposable.Dispose();
            }
        }
예제 #37
0
        private static void ExtractInterfaces(ModuleDefinition module, TypeDefinition targetDependency, TypeDefinition targetType, IDependencyScope scope)
        {
            //var methodMap = new Dictionary<MethodReference, MethodReference>();

            //var interfaceName = string.Format("I{0}", targetDependency.Name);
            //var namespaceName = targetType.Namespace;

            //var methodFinder = new MethodFinder();
            //var methodFilter = new InvokedMethodFilter();
            //var addInterfaceMethod = new AddInterfaceMethod();
            //var addAdapterMethod = new AddAdapterMethod();
            //var injectAdapterAsParameter = new InjectAdapterAsParameter();
            //var callFilter = new InvalidCallFilter();
            //var popMethodArguments = new PopMethodArguments();

            //var methodBuilder = new AddInterfaceMethodIfMethodNotFound(methodFinder, addInterfaceMethod);
            //var createInterfaceType = new CreateInterfaceType(methodFilter,
            //    methodBuilder,
            //    scope,
            //    targetDependency,
            //    module);
            //var interfaceType = createInterfaceType.CreateType(interfaceName,
            //                                              namespaceName,
            //                                              methodMap);

            //var modifiedMethods = new HashSet<MethodReference>();
            //var modifiedConstructors = new HashSet<MethodReference>();

            //var extractor = new DependencyExtractor(interfaceType, methodMap, modifiedMethods, modifiedConstructors);
            //extractor.Extract(targetDependency, targetType.Module, scope);

            ////// Step 9: Create an adapter that maps the calls back to the interface

            //var extractionContext = new ExtractionContext(interfaceType, targetDependency, methodMap);
            //var addAdapterConstructor = new AddAdapterConstructor(extractionContext);
            //var createAdapterType = new CreateAdapterType(module, targetDependency, interfaceType, addAdapterConstructor, addAdapterMethod);
            //var adapterBuilder = new AdapterBuilder(extractionContext);

            //var pushParameter = new PushParameterOntoArgumentStack(injectAdapterAsParameter);
            //var pushMethodArguments = new PushMethodArguments(adapterBuilder, pushParameter, new ExtractionContext(interfaceType, targetDependency, methodMap));

            //var replaceMethodCall = new InjectInterfaceMethodCall(pushMethodArguments, popMethodArguments);
            //var replaceMethodBody = new ReplaceMethodCalls(module, replaceMethodCall, callFilter);

            //var updater = new DependencyUpdater(replaceMethodBody);
            ////// Step 10: Scan the rest of the assembly and create an instance of the adapter at each method call site
            //updater.UpdateAffectedMethods(scope.Methods, modifiedConstructors, methodMap);
        }
예제 #38
0
        protected virtual Customer GetCustomerByGuId(IDependencyScope dependencyScope, string customerGuId)
        {
            Customer customer = null;

            try
            {
                var customerService = dependencyScope.GetService <ICustomerService>();
                customer = customerService.GetCustomerByGuid(Guid.Parse(customerGuId));
            }
            catch (Exception exception)
            {
                exception.Dump();
            }

            return(customer);
        }
        public WindsorDependencyScope(IDependencyScope scope, Action <object> releaseAction)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

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

            _scope           = scope;
            _releaseActions  = releaseAction;
            _objectInstances = new List <object>();
        }
예제 #40
0
        protected virtual bool HasPermission(IDependencyScope dependencyScope, Customer customer)
        {
            var result = true;

            if (Permission.HasValue())
            {
                try
                {
                    var permissionService = (IPermissionService)dependencyScope.GetService(typeof(IPermissionService));
                    result = permissionService.Authorize(Permission, customer);
                }
                catch { }
            }

            return(result);
        }
        public ReleasingDependencyScope(IDependencyScope scope, Action <object> release)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

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

            this.scope   = scope;
            this.release = release;
            instances    = new List <object>();
        }
예제 #42
0
        protected virtual Customer GetCustomer(IDependencyScope dependencyScope, int customerId)
        {
            Customer customer = null;

            try
            {
                var customerService = dependencyScope.GetService <ICustomerService>();
                customer = customerService.GetCustomerById(customerId);
            }
            catch (Exception exception)
            {
                exception.Dump();
            }

            return(customer);
        }
        public ReleasingDependencyScope(IDependencyScope scope, Action<object> release)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

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

            this.scope = scope;
            this.release = release;
            instances = new List<object>();
        }
        static RestrictedUacContractService ResolveService(HttpActionExecutedContext context)
        {
            IDependencyScope scope = context.Request.GetDependencyScope();

            if (scope == null)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
            object service = scope.GetService(typeof(RestrictedUacContractService));

            if (service == null)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
            return((RestrictedUacContractService)service);
        }
예제 #45
0
        public void SwapDependencies(IDependencyScope scope, TypeDefinition targetDependency)
        {
            var targetMethods = scope.Methods;
            foreach (var method in targetMethods)
            {
                if (method.IsAbstract || !method.HasBody)
                    continue;

                var body = method.Body;
                body.InitLocals = true;
                var oldInstructions = body.Instructions.Cast<Instruction>().ToList();
                body.Instructions.Clear();

                SwapMethods(body, oldInstructions, _methodMap, targetDependency);
            }
        }
		public PipelineBuilder(
			[NotNull]BusSettings busSettings,
			[NotNull]IHandlerProvider handlerProvider,
			[NotNull]IGlobalPipelineProvider globalPipelineProvider,
			[NotNull]IGlobalPipelineTracker tracker,
			[NotNull]IDependencyScope dependencyScope)
		{
			if (handlerProvider == null) throw new ArgumentNullException(nameof(handlerProvider));
			if (globalPipelineProvider == null) throw new ArgumentNullException(nameof(globalPipelineProvider));
			if (tracker == null) throw new ArgumentNullException(nameof(tracker));
			if (dependencyScope == null) throw new ArgumentNullException(nameof(dependencyScope));
			if (busSettings == null) throw new ArgumentNullException(nameof(busSettings));

			this.handlerProvider = handlerProvider;
			this.globalPipelineProvider = globalPipelineProvider;
			this.tracker = tracker;
			this.dependencyScope = dependencyScope;
			this.busSettings = busSettings;
		}
        public void SwapDependencies(IDependencyScope scope, TypeDefinition targetDependency)
        {
            var methods = scope.Methods;
            foreach (var method in methods.Cast<MethodDefinition>())
            {
                if (method.IsAbstract || !method.HasBody)
                    continue;

                var body = method.Body;
                var locals = body.Variables.Cast<VariableDefinition>();

                foreach (var local in locals)
                {
                    if (local.VariableType != targetDependency)
                        continue;

                    local.VariableType = _interfaceType;
                }
            }
        }
        static void DispatchCore(ExceptionFilter filter, Exception exception, JobContext context, 
            IDependencyScope scope)
        {
            var instance = scope.GetService(filter.Type);

            foreach (var argument in filter.Arguments)
            {
                var exceptionContext = argument as ExceptionContext;
                if (exceptionContext != null)
                {
                    exceptionContext.ActivityType = context.ActivityType;
                    exceptionContext.Method = context.Method;
                    exceptionContext.Arguments = context.Arguments;
                    exceptionContext.Exception = exception;
                    exceptionContext.DispatchCount = context.DispatchCount;
                }
            }

            var method = filter.Type.GetMethod(filter.Method);
            method.Invoke(instance, filter.Arguments);
        }
        public void Dispatch(Job job, Exception exception, JobContext context, IDependencyScope scope)
        {
            if (job == null) throw new ArgumentNullException("job");
            if (exception == null) throw new ArgumentNullException("exception");
            if (context == null) throw new ArgumentNullException("context");
            if (scope == null) throw new ArgumentNullException("scope");

            foreach (var filter in job.ExceptionFilters)
            {
                try
                {
                    DispatchCore(filter, exception, context, scope);
                }
                catch (Exception e)
                {
                    if (e.IsFatal())
                        throw;

                    _eventStream.Publish<ExceptionFilterDispatcher>(e);
                }
            }
        }
        /// <summary>
        /// Provides any FluentValidation Validators appropriate for validating the specified type.  These will have
        /// been created within the specified Dependency Scope
        /// </summary>
        /// <param name="type">Model type to find validators for</param>
        /// <param name="scope">Scope to create validators from</param>
        /// <returns></returns>
        public IEnumerable<IValidator> GetValidators(Type type, IDependencyScope scope)
        {
            Trace.TraceInformation("GetValidators: {0}", type.FullName);

            if (_typesWithNoValidators.Contains(type))
            {
                return Enumerable.Empty<IValidator>();
            }

            IValidator validator = null;
            Type validatorType = typeof(IValidator<>).MakeGenericType(type);

            if (!_typesWithValidators.Contains(type))
            {
                // We've not checked this type before.  Look for a validator and store whether we have one
                lock (_syncRoot)
                {
                    validator = _factory.GetValidator(validatorType, scope);
                    if (validator == null)
                    {
                        _typesWithNoValidators.Add(type);
                        return Enumerable.Empty<IValidator>();
                    }
                    else
                    {
                        _typesWithValidators.Add(type);
                    }
                }
            }

            // There should be a validator available for this type
            if (validator == null)
            {
                validator = scope.GetService(validatorType) as IValidator;
            }
            return new[] { validator };
        }
 public void Dispose()
 {
     scope.Dispose();
     scope = null;
 }
 public void Initialize()
 {
     var container = new WebContainer();
     _dependencyScope = new CodemashNinjectDependencyResolver(container);
 }
 /// <summary>
 /// Get <see cref="ICacheResponseBuilder" /> from <see cref="IDependencyScope" />
 /// </summary>
 /// <param name="scope"></param>
 /// <returns></returns>
 protected virtual ICacheResponseBuilder GetCacheResponseBuilder(IDependencyScope scope)
 {
     return scope.GetService(typeof(ICacheResponseBuilder)) as ICacheResponseBuilder ??
            new CacheResponseBuilder();
 }
예제 #54
0
 private static void AddPluginProfiles(List<Profile> profiles, IDependencyScope dependencyResolver)
 {
     var pluginConfiguration = (IPluginConfiguration)dependencyResolver.GetService(typeof(IPluginConfiguration));
     profiles.AddRange(pluginConfiguration.GetAutoMapperProfiles());
 }
 public ICacheStrategy GetCacheStrategyPublic(IDependencyScope scope, _IInvocation invocation, IDictionary<string, object> invocationContext)
 {
     return GetCacheStrategy(scope, invocation, invocationContext);
 }
 /// <summary>
 /// Get <see cref="ICacheStrategy" /> from <see cref="IDependencyScope" />
 /// </summary>
 /// <param name="scope"></param>
 /// <param name="invocation"></param>
 /// <param name="invocationContext"></param>
 /// <returns></returns>
 protected virtual ICacheStrategy GetCacheStrategy(IDependencyScope scope, _IInvocation invocation, IDictionary<string, object> invocationContext)
 {
     var strategy = CacheStrategyType != null ? scope.GetService(CacheStrategyType) as ICacheStrategy : null;
     if (strategy == null)
     {
         var strategyProvider = scope.GetService(typeof (ICacheStrategyProvider)) as ICacheStrategyProvider ?? Global.CacheStrategyProvider;
         strategy = strategyProvider.GetStrategy(invocation, invocationContext);
     }
     if (strategy == null) throw new Exception("Cannot find caching strategy for this request");
     return strategy;
 }
 public ICacheResponseBuilder GetCacheResponseBuilderPublic(IDependencyScope scope)
 {
     return GetCacheResponseBuilder(scope);
 }
예제 #58
0
        private static void SeedServer(IDependencyScope scope)
        {
            var userManager = (IHaloUserManager) scope.GetService(typeof (IHaloUserManager));
            var userBaseDataRepository = (IUserBaseDataRepository) scope.GetService(typeof (IUserBaseDataRepository));
            var userSubscriptionRepository = (IUserSubscriptionRepository)scope.GetService(typeof(IUserSubscriptionRepository));
            var clanRepository = (IClanRepository)scope.GetService(typeof(IClanRepository));
            var clanMembershipRepository = (IClanMembershipRepository) scope.GetService(typeof (IClanMembershipRepository));

            try
            {
                var clan = clanRepository.FindByNamePrefixAsync("Clan1").Result.FirstOrDefault();
                if (clan == null)
                {
                    clan = new Clan
                    {
                        Name = "Clan1",
                        Description = "First clan",
                        Tag = "TAG"
                    };
                    clanRepository.CreateAsync(clan).Wait();
                }

                HaloUser testUser1 = new HaloUser
                {
                    UserName = "******"
                };
                HaloUser testUser2 = new HaloUser
                {
                    UserName = "******"
                };

                userManager.CreateAsync(testUser1, "123").Wait();
                userManager.CreateAsync(testUser2, "test").Wait();

                UserBaseData testUser1Data = new UserBaseData
                {
                    User = new UserId
                    {
                        Id = testUser1.UserId
                    },
                    Nickname = "User1",
                    Clan = new ClanId
                    {
                        Id = 0
                    },
                    ClanTag = "",
                    Level = 2,
                    BattleTag = "BattleTag1"
                };

                UserBaseData testUser2Data = new UserBaseData
                {
                    User = new UserId
                    {
                        Id = testUser2.UserId
                    },
                    Nickname = "User2",
                    Clan = new ClanId
                    {
                        Id = 0
                    },
                    ClanTag = "",
                    Level = 10,
                    BattleTag = "BattleTag2"
                };

                userBaseDataRepository.SetUserBaseDataAsync(testUser1Data);
                userBaseDataRepository.SetUserBaseDataAsync(testUser2Data);

                var testUser1ClanMembership = new ClanMembership
                {
                    UserId = testUser1.UserId,
                    ClanId = clan.ClanId,
                    Role = 1
                };

                clanMembershipRepository.CreateAsync(testUser1ClanMembership).Wait();

                var testUser1Subscription = new UserSubscription
                {
                    UserId = testUser1.UserId,
                    FriendUserId = testUser2.UserId
                };
                userSubscriptionRepository.CreateAsync(testUser1Subscription).Wait();

            }
            catch (Exception)
            {
                Debug.WriteLine("Server initialization failed.");
            }
        }
 public WindsorDependencyScope(IWindsorContainer container, IDependencyScope scope)
 {
     _container = container;
     _scope = scope;
 }
예제 #60
0
 public DashboardBuilder(IDependencyScope dependencyScope)
 {
     _dependencyScope = dependencyScope;
     _dashboardMappingsProvider = (IDashboardMappingsProvider)_dependencyScope.GetService(typeof(IDashboardMappingsProvider));
 }