Пример #1
0
        public void Global_Middleware_Executes()
        {
            _mockInteractor = Substitute.For <IInteractor <MockUseCase, IMockOutputPort> >();
            _handlerResolver.ResolveInteractor <MockUseCase, IMockOutputPort>(Arg.Any <MockUseCase>()).Returns(_mockInteractor);

            var globalMiddleware = Substitute.For <IMiddleware>();

            globalMiddleware.Execute(
                Arg.Any <MockUseCase>(),
                d => Task.FromResult(new UseCaseResult(true)),
                Arg.Any <CancellationToken>())
            .ReturnsForAnyArgs(x => new UseCaseResult(true))
            .AndDoes(x =>
            {
                x.Arg <Func <MockUseCase, Task <UseCaseResult> > >().Invoke(x.Arg <MockUseCase>());
            });
            IReadOnlyList <IMiddleware> globalPipeline = new List <IMiddleware> {
                globalMiddleware
            };

            _handlerResolver.ResolveGlobalMiddleware().Returns(globalPipeline);

            _interactorHub.Execute(new MockUseCase(), (IMockOutputPort) new MockOutputPort());

            globalMiddleware.Received().Execute(
                Arg.Any <MockUseCase>(),
                Arg.Any <Func <MockUseCase, Task <UseCaseResult> > >(),
                Arg.Any <CancellationToken>());
        }
Пример #2
0
        public Task <UseCaseResult> Execute <TUseCase, TOutputPort>(TUseCase useCase, TOutputPort outputPort, CancellationToken cancellationToken)
            where TUseCase : IUseCase <TOutputPort>
        {
            if (useCase == null)
            {
                throw new UseCaseNullException("The usecase cannot be null");
            }

            if (outputPort == null)
            {
                throw new OutputPortNullException("The output port cannot be null");
            }

            var interactor = _resolver.ResolveInteractor <TUseCase, TOutputPort>(useCase);
            var pipeline   = new List <IMiddleware <TUseCase, TOutputPort> >();

            pipeline.AddRange(_resolver.ResolveGlobalMiddleware().Select(x => new GlobalMiddlewareWrapper <TUseCase, TOutputPort>(x)));
            pipeline.AddRange(_resolver.ResolveMiddleware <TUseCase>().Select(x => new MiddlewareWrapper <TUseCase, TOutputPort>(x)));
            pipeline.AddRange(_resolver.ResolveMiddleware <TUseCase, TOutputPort>(useCase).ToList());

            var pipelineRoot = pipeline.FirstOrDefault();

            if (pipelineRoot == null)
            {
                return(interactor.Execute(useCase, outputPort, cancellationToken));
            }

            pipeline.Add(new InteractorMiddlewareWrapper <TUseCase, TOutputPort>(interactor));

            var currentMiddleWare = 1;

            Task <UseCaseResult> NextMiddleWare(TUseCase usecase)
            => pipeline[currentMiddleWare++].Execute(usecase, outputPort, NextMiddleWare, cancellationToken);

            return(pipelineRoot.Execute(useCase, outputPort, NextMiddleWare, cancellationToken));
        }