Repository navigation
[WIP] IServiceProvider on runspace - #17349
Staffan Gustafsson (powercode) wants to merge 6 commits into
Conversation
| { | ||
| get => _sessionState.ExecutionContext.ServiceProvider; | ||
| set => _sessionState.ExecutionContext.ServiceProvider = value; | ||
| } |
There was a problem hiding this comment.
Having this API on PSModuleInfo makes it seem like any module can use this to set their own service provider. If two modules try to set up different service providers, then the last loaded will win and the other will break.
Have you considered using a ConditionalWeakTable<PSModuleInfo, IServiceProvider>?
There was a problem hiding this comment.
Having lower-level modules be able to rebuild a service provider with additional services may be useful.
But perhaps something that should be made more specific?
The use case I want to cover is to be able to set an initial service provider from the InitialSessionState and make it possible to have modules recreate it with some added services.
That could perhaps be abstracted with a get only IServiceProvider property, and some
IServiceProvider ServiceProvider { get; }
void AddServices(IServiceCollection services)But in that case, I think we would have to commit to some implementation of IServiceProvider.
There was a problem hiding this comment.
I still think it'll be potentially challenging for different module authors to use the same instance. Especially if they find themselves in a runspace with a different implementation.
What I was getting at with the weak table suggestion, you could have a common assembly with code like this:
namespace MyOrg
{
public static class Services
{
private static readonly ConditionalWeakTable<Runspace, IServiceProvider> s_services = new();
[Hidden, EditorBrowsable(EditorBrowsableState.Never)]
public static void SetInternal(Runspace runspace, IServiceProvider testProvider) => s_services.AddOrUpdate(runspace, testProvider);
public static IServiceProvider Get(Runspace runspace) => s_services.GetValue(runspace, Create);
public static IServiceProvider GetFromTLS() => s_services.GetValue(Runspace.DefaultRunspace, Create);
private static IServiceProvider Create(Runspace key)
{
return s_isTesting ? new TestingServiceProvider() : new ServiceProvider();
}
}
}
public class Tests
{
[TestMethod]
public void CanSearchItem()
{
var restClient = new Mock<IJiraRestClient>();
restClient.Setup(c => c.ExecuteRequestAsync(Method.POST, "rest/api/2/search", It.IsAny<object>(), It.IsAny<CancellationToken>()))
.Returns(() => Task.FromResult(JToken.Parse(SR.SearchResultABC)))
.Verifiable();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IJiraRestClient>(restClient.Object);
var provider = serviceCollection.BuildServiceProvider();
var iss = InitialSessionState.CreateDefault2();
iss.ImportPSModulesFromPath(typeof(SearchJiraIssue).Assembly.Location);
using var ps = PowerShell.Create(iss);
Services.SetInternal(ps.Runspace, provider);
CmdletInfo searchInfo = new CmdletInfo(@"Jira\Search-JiraIssue", typeof(SearchJiraIssue));
ps.AddCommand(searchInfo);
ps.AddParameter(nameof(SearchJiraIssue.ProjectKey), "ABC");
var results = ps.Invoke<Atlassian.Jira.Issue>();
restClient.Verify();
// Assert on results
}
}There was a problem hiding this comment.
That is quite similar to what I have been using (not with a ConditionalWeakTable, good suggestion!)
but that doesn't really help with injecting something differently in tests, or am I missing something?
There was a problem hiding this comment.
Updated with how I'd handle a different service provider for tests. Could also just go with a static property that's like ServiceProviderOverride.
If that doesn't answer your question, can you provide an example of how you'd use it with the proposal for tests?
There was a problem hiding this comment.
Each test registers its own interfaces with the ServiceProvider. That is up to each test, and not the responsibility of the Services class.
So the question for me has been how to propagate the service provider for each test.
A test could look like this:
[TestMethod]
public void CanSearchItem()
{
var restClient = new Mock<IJiraRestClient>();
restClient.Setup(c => c.ExecuteRequestAsync(Method.POST, "rest/api/2/search", It.IsAny<object>(), It.IsAny<CancellationToken>()))
.Returns(() => Task.FromResult(JToken.Parse(SR.SearchResultABC)))
.Verifiable();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IJiraRestClient>(restClient.Object);
var provider = serviceCollection.BuildServiceProvider();
var iss = InitialSessionState.CreateDefault2();
iss.ImportPSModulesFromPath(typeof(SearchJiraIssue).Assembly.Location);
iss.ServiceProvider = provider;
using var ps = PowerShell.Create(iss);
CmdletInfo searchInfo = new CmdletInfo(@"Jira\Search-JiraIssue", typeof(SearchJiraIssue));
ps.AddCommand(searchInfo);
ps.AddParameter(nameof(SearchJiraIssue.ProjectKey), "ABC");
var results = ps.Invoke<Atlassian.Jira.Issue>();
restClient.Verify();
// Assert on results
} And the cmdlet could do:
protected override void EndProcessing()
{
var restClient = SessionState.ServiceProvider?.GetService<IJiraRestClient>() ?? new JiraRestClient();
var restBody = BuildRestBody();
var issues = restClient.SearchIssues(restBody);
foreach (var issue in issues)
{
WriteObject(issue);
}
}There was a problem hiding this comment.
It is possible to work around this, as you pointed out, with some static map where I could register the runspace mapped to a service provider, but then either all modules would need such a mapping, or share some common library.
By adding this to the SessionState, it seems things become much simpler.
There was a problem hiding this comment.
Yeah I went ahead and updated my example for that. I agree that it'd be ideal to build in a good way to do DI but I'm not sure what pattern we could use to fit all use cases.
If we go this route, I worry that two separate modules trying to do their own DI will end up stepping on each other. I'd ideally like the service provider to be unique to the module instance, but that doesn't fit your use case either.
I think a common library or module is the easiest solution to this problem without some concept of "module groups" in the engine.
There was a problem hiding this comment.
An alternative may be to have SessionState provide a PowerShell defined interface, where there is only a getter for the service provider, and some method like
public interface IServices{
IServiceProvider ServiceProvider {get;}
void AddServicesAndRebuildProvider(IServiceCollection services);
}Then there can only ever be a single ServiceProvider, but you can add services on a per-module basis.
There was a problem hiding this comment.
Yeah but I'm thinking if two modules are using a common library and they both register services of the same interface then that'll become an issue still
|
This PR has Quantification details
Why proper sizing of changes matters
Optimal pull request sizes drive a better predictable PR flow as they strike a
What can I do to optimize my changes
How to interpret the change counts in git diff output
Was this comment helpful? 👍 :ok_hand: :thumbsdown: (Email) |
|
This pull request has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 15 days. It will be closed if no further activity occurs within 10 days of this comment. |
PR Summary
PR Context
PR Checklist
.h,.cpp,.cs,.ps1and.psm1files have the correct copyright headerWIP:or[ WIP ]to the beginning of the title (theWIPbot will keep its status check atPendingwhile the prefix is present) and remove the prefix when the PR is ready.(which runs in a different PS Host).