前两篇看到了很多这样的代码:
OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
得到了OleMenuCommandService这个服务对象,那我们也学着自己定义Service
1.首先定义一个接口和一个markup type 接口:
[Guid("D7524CAB-5029-402d-9591-FA0D59BBA0F0")] [ComVisible(true)] public interface ICalculationService { bool ShowMessage(string message); } [Guid("AF7F72EF-2B54-4798-B76A-21DC02CC04B7")] public interface SCalculationService { }
其中服务接口以“I”开头,标记接口以“S”开头。它们必须能够被COM识别,所以要加上Guid。另外,服务接口必须定义为ComVisible,这样非托管代码就可以检索到它。
2.创建实现接口的服务:
public sealed class CalculationService : ICalculationService, SCalculationService { public bool ShowMessage(string message) { MessageBox.Show(message); return true; } }
3.修改vspackage:
在package那里附加一个attribute,以声明该package能提供的服务:
[ProvideService(typeof(SCalculationService))] public sealed class VSPackageEmptyPackage : Package
添加初始化代码:
public VSPackageEmptyPackage() { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString())); IServiceContainer serviceContainer = this; ServiceCreatorCallback creationCallback = CreateService; serviceContainer.AddService(typeof(SCalculationService), creationCallback, true); }
添加CreateService方法:
private object CreateService(IServiceContainer container, Type serviceType) { if (container != this) { return null; } if (typeof(SCalculationService) == serviceType) { return new CalculationService(); } return null; }
这样我们就能在初始化package后调用了:
ICalculationService calcService = Package.GetGlobalService(typeof(SCalculationService)) as ICalculationService; if (calcService != null) { calcService.ShowMessage("calcService"); }