Exemple #1
0
        private void SendMessage(string pluginId, PluginResponseMessage message)
        {
            var messageBroker = new PluginMessageBroker(pluginId, _sendMessageMethod);

            messageBroker.SendMessage(message);
        }
Exemple #2
0
        private PluginResponseMessage RegisterPlugin(
            PluginMessage message,
            IAssemblyLoadContext assemblyLoadContext)
        {
            var registerData = message.Data.ToObject<PluginRegisterData>();
            var response = new PluginResponseMessage
            {
                MessageName = RegisterPluginMessageName
            };

            var pluginId = message.PluginId;
            var registerDataTypeCacheKey = registerData.GetFullTypeCacheKey();
            IPlugin plugin;
            Type pluginType;

            if (!_pluginTypeCache.TryGetValue(registerDataTypeCacheKey, out pluginType))
            {
                try
                {
                    Assembly assembly;
                    if (!_assemblyCache.TryGetValue(registerData.AssemblyName, out assembly))
                    {
                        assembly = assemblyLoadContext.Load(registerData.AssemblyName);
                    }

                    pluginType = assembly.GetType(registerData.TypeName);
                }
                catch (Exception exception)
                {
                    response.Error = exception.Message;

                    return response;
                }
            }

            if (pluginType == null)
            {
                response.Error = Resources.FormatPlugin_TypeCouldNotBeLocatedInAssembly(
                    pluginId,
                    registerData.TypeName,
                    registerData.AssemblyName);

                return response;
            }
            else
            {
                // We build out a custom plugin service provider to add a PluginMessageBroker and
                // IAssemblyLoadContext to the potential services that can be used to construct an IPlugin.
                var pluginServiceProvider = new PluginServiceProvider(
                    _hostServices,
                    messageBroker: new PluginMessageBroker(pluginId, _sendMessageMethod));

                plugin = ActivatorUtilities.CreateInstance(pluginServiceProvider, pluginType) as IPlugin;

                if (plugin == null)
                {
                    response.Error = Resources.FormatPlugin_CannotProcessMessageInvalidPluginType(
                        pluginId,
                        pluginType.FullName,
                        typeof(IPlugin).FullName);

                    return response;
                }
            }

            Debug.Assert(plugin != null);

            _registeredPlugins[pluginId] = plugin;

            response.Success = true;

            return response;
        }