Why does ServiceProvider.GlobalProvider.GetService always return null in my command handler? #489
Answered
by
reduckted
aglasencnik
asked this question in
Q&A
-
Hi, I have a quick question.... I have a CommandHandler: public bool ExecuteCommand(SaveCommandArgs args, CommandExecutionContext executionContext)
{
try
{
var fileName = args.SubjectBuffer.GetFileName();
if (string.IsNullOrWhiteSpace(fileName))
return false;
var fileExtension = Path.GetExtension(fileName);
if (string.IsNullOrWhiteSpace(fileExtension) || fileExtension.ToLower() != ".dot")
return false;
ThreadHelper.ThrowIfNotOnUIThread();
var package = ServiceProvider.GlobalProvider.GetService(typeof(GraphvizVSPackage)) as GraphvizVSPackage;
if (package is null)
return false;
var window = package.FindToolWindow(typeof(GraphPreviewWindowControl), 0, true);
if (window is null)
return false;
var control = window.Content as GraphPreviewWindowControl;
if (control is null)
return false;
control.UpdatePreviewWindow(fileName);
return false;
}
catch (Exception ex)
{
ex.Log();
return false;
}
} But: |
Beta Was this translation helpful? Give feedback.
Answered by
reduckted
Jan 28, 2024
Replies: 1 comment 7 replies
-
A package is not registered as a service, which is why it can't be retrieved using Where are you creating the command handler? Can you pass the package into the command handler's constructor? |
Beta Was this translation helpful? Give feedback.
7 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ah, it's a MEF export. 🤦♂️ Sorry, I got myself confused between the
ICommandHandler
and the command interceptors in the toolkit.Since it's a MEF export, you won't be able to pass the package to the constructor like I suggested, however you should be able to register the package as a service. Doing that will mean you can retrieve it using
GetService
.On your package, add this attribute:
And then in the
InitializeAsync
method, add the service: