diff --git a/src/Behavioral.Automation/Hooks/BeforeStep/PageScopeObserverBinding.cs b/src/Behavioral.Automation/Hooks/BeforeStep/PageScopeObserverBinding.cs new file mode 100644 index 00000000..cc9dd80c --- /dev/null +++ b/src/Behavioral.Automation/Hooks/BeforeStep/PageScopeObserverBinding.cs @@ -0,0 +1,30 @@ +using Behavioral.Automation.Services; +using Behavioral.Automation.Services.Mapping.Contract; +using JetBrains.Annotations; +using System; +using TechTalk.SpecFlow; + +namespace Behavioral.Automation.Hooks.BeforeStep +{ + /// + /// Allows to automatically switch PageContext, depending on current Driver url + /// + [Binding] + public class PageScopeObserverBinding + { + private readonly IScopeContextManager _scopeContextManager; + private readonly IDriverService _driverService; + + public PageScopeObserverBinding([NotNull] IScopeContextManager scopeContextManager, [NotNull] IDriverService driverService) + { + _scopeContextManager = scopeContextManager; + _driverService = driverService; + } + + [BeforeStep] + public void SwitchContextToCurrentUrl() + { + _scopeContextManager.SwitchToCurrentUrl(new Uri(_driverService.CurrentUrl)); + } + } +} diff --git a/src/Behavioral.Automation/Services/Mapping/Contract/IScopeContextManager.cs b/src/Behavioral.Automation/Services/Mapping/Contract/IScopeContextManager.cs index 6309639c..3b8b769c 100644 --- a/src/Behavioral.Automation/Services/Mapping/Contract/IScopeContextManager.cs +++ b/src/Behavioral.Automation/Services/Mapping/Contract/IScopeContextManager.cs @@ -7,5 +7,6 @@ public interface IScopeContextManager void SwitchPage(Uri uri); IScopeContextRuntime UseControlScopeContextRuntime(ControlScopeSelector controlScopeSelector); void SwitchPage(string pageName); + void SwitchToCurrentUrl(Uri currentUrl); } } \ No newline at end of file diff --git a/src/Behavioral.Automation/Services/Mapping/ScopeContextManager.cs b/src/Behavioral.Automation/Services/Mapping/ScopeContextManager.cs index c12fba51..43fe39ca 100644 --- a/src/Behavioral.Automation/Services/Mapping/ScopeContextManager.cs +++ b/src/Behavioral.Automation/Services/Mapping/ScopeContextManager.cs @@ -7,6 +7,8 @@ public sealed class ScopeContextManager : IScopeContextManager { private readonly IScopeContextRuntime _scopeContextRuntime; private readonly IUriToPageScopeMapper _uriToPageScopeMapper; + private Uri LastVisitedUrl = default; + private readonly Uri EmptyPageUrl = new Uri("data:,"); public ScopeContextManager(IScopeContextRuntime scopeContextRuntime, IUriToPageScopeMapper uriToPageScopeMapper) { @@ -41,5 +43,14 @@ public void SwitchPage(string pageName) var pageScopeContext = _uriToPageScopeMapper.GetPageScopeContext(pageName); _scopeContextRuntime.SwitchToPageScope(pageScopeContext); } + + public void SwitchToCurrentUrl(Uri currentUrl) + { + if (currentUrl == EmptyPageUrl || currentUrl == LastVisitedUrl) + return; + + SwitchPage(currentUrl); + LastVisitedUrl = currentUrl; + } } } \ No newline at end of file