示例#1
0
        public void ReturnsServiceProviderFromWrappedScope()
        {
            var wrappedScope = new FakeSyncServiceScope();
            var asyncScope   = new AsyncServiceScope(wrappedScope);

            Assert.Same(wrappedScope.ServiceProvider, asyncScope.ServiceProvider);
        }
            public IServiceScope CreateScope()
            {
                var scope = new AsyncServiceScope(_serviceProvider.GetService <IServiceScopeFactory>().CreateScope());

                Scopes.Add(scope);
                return(scope);
            }
示例#3
0
        public async ValueTask CallsDisposeOnWrappedSyncScopeOnDisposeAsync()
        {
            var wrappedScope = new FakeSyncServiceScope();
            var asyncScope   = new AsyncServiceScope(wrappedScope);

            await asyncScope.DisposeAsync();

            Assert.True(wrappedScope.DisposeCalled);
        }
示例#4
0
        public void CallsDisposeOnWrappedSyncScopeOnDispose()
        {
            var wrappedScope = new FakeSyncServiceScope();
            var asyncScope   = new AsyncServiceScope(wrappedScope);

            asyncScope.Dispose();

            Assert.True(wrappedScope.DisposeCalled);
        }
示例#5
0
        internal WebAssemblyHost(
            WebAssemblyHostBuilder builder,
            IServiceProvider services,
            AsyncServiceScope scope,
            string?persistedState)
        {
            // To ensure JS-invoked methods don't get linked out, have a reference to their enclosing types
            GC.KeepAlive(typeof(JSInteropMethods));

            _services       = services;
            _scope          = scope;
            _configuration  = builder.Configuration;
            _rootComponents = builder.RootComponents;
            _persistedState = persistedState;
        }
示例#6
0
    public CircuitHost(
        CircuitId circuitId,
        AsyncServiceScope scope,
        CircuitOptions options,
        CircuitClientProxy client,
        RemoteRenderer renderer,
        IReadOnlyList <ComponentDescriptor> descriptors,
        RemoteJSRuntime jsRuntime,
        RemoteNavigationManager navigationManager,
        CircuitHandler[] circuitHandlers,
        ILogger logger)
    {
        CircuitId = circuitId;
        if (CircuitId.Secret is null)
        {
            // Prevent the use of a 'default' secret.
            throw new ArgumentException($"Property '{nameof(CircuitId.Secret)}' cannot be null.", nameof(circuitId));
        }

        _scope             = scope;
        _options           = options ?? throw new ArgumentNullException(nameof(options));
        Client             = client ?? throw new ArgumentNullException(nameof(client));
        Renderer           = renderer ?? throw new ArgumentNullException(nameof(renderer));
        Descriptors        = descriptors ?? throw new ArgumentNullException(nameof(descriptors));
        JSRuntime          = jsRuntime ?? throw new ArgumentNullException(nameof(jsRuntime));
        _navigationManager = navigationManager ?? throw new ArgumentNullException(nameof(navigationManager));
        _circuitHandlers   = circuitHandlers ?? throw new ArgumentNullException(nameof(circuitHandlers));
        _logger            = logger ?? throw new ArgumentNullException(nameof(logger));

        Services = scope.ServiceProvider;

        Circuit = new Circuit(this);
        Handle  = new CircuitHandle()
        {
            CircuitHost = this,
        };

        // An unhandled exception from the renderer is always fatal because it came from user code.
        Renderer.UnhandledException += ReportAndInvoke_UnhandledException;
        Renderer.UnhandledSynchronizationException += SynchronizationContext_UnhandledException;

        JSRuntime.UnhandledException += ReportAndInvoke_UnhandledException;

        _navigationManager.UnhandledException += ReportAndInvoke_UnhandledException;
    }
示例#7
0
        public PageContext(
            Dispatcher dispatcher,
            AsyncServiceScope serviceScope,
            IpcSender ipcSender,
            string baseUrl,
            string startUrl)
        {
            _serviceScope = serviceScope;
            var services = serviceScope.ServiceProvider;

            NavigationManager = (WebViewNavigationManager)services.GetRequiredService <NavigationManager>();
            NavigationManager.AttachToWebView(ipcSender, baseUrl, startUrl);

            JSRuntime = (WebViewJSRuntime)services.GetRequiredService <IJSRuntime>();
            JSRuntime.AttachToWebView(ipcSender);

            var loggerFactory = services.GetRequiredService <ILoggerFactory>();

            Renderer = new WebViewRenderer(services, dispatcher, ipcSender, loggerFactory, JSRuntime.ElementReferenceContext);
        }
示例#8
0
    public PageContext(
        Dispatcher dispatcher,
        AsyncServiceScope serviceScope,
        IpcSender ipcSender,
        JSComponentConfigurationStore jsComponentsConfiguration,
        string baseUrl,
        string startUrl)
    {
        _serviceScope = serviceScope;
        var services = serviceScope.ServiceProvider;

        NavigationManager = (WebViewNavigationManager)services.GetRequiredService <NavigationManager>();
        NavigationManager.AttachToWebView(ipcSender, baseUrl, startUrl);

        JSRuntime = (WebViewJSRuntime)services.GetRequiredService <IJSRuntime>();
        JSRuntime.AttachToWebView(ipcSender);

        var loggerFactory = services.GetRequiredService <ILoggerFactory>();
        var jsComponents  = new JSComponentInterop(jsComponentsConfiguration);

        Renderer = new WebViewRenderer(services, dispatcher, ipcSender, loggerFactory, JSRuntime, jsComponents);
    }
示例#9
0
        public CircuitHost(
            CircuitId circuitId,
            AsyncServiceScope scope,
            CircuitOptions options,
            CircuitClientProxy client,
            RemoteRenderer renderer,
            IReadOnlyList <ComponentDescriptor> descriptors,
            RemoteJSRuntime jsRuntime,
            CircuitHandler[] circuitHandlers,
            ILogger logger)
        {
            CircuitId = circuitId;
            if (CircuitId.Secret is null)
            {
                // Prevent the use of a 'default' secret.
                throw new ArgumentException(nameof(circuitId));
            }

            _scope           = scope;
            _options         = options ?? throw new ArgumentNullException(nameof(options));
            Client           = client ?? throw new ArgumentNullException(nameof(client));
            Renderer         = renderer ?? throw new ArgumentNullException(nameof(renderer));
            Descriptors      = descriptors ?? throw new ArgumentNullException(nameof(descriptors));
            JSRuntime        = jsRuntime ?? throw new ArgumentNullException(nameof(jsRuntime));
            _circuitHandlers = circuitHandlers ?? throw new ArgumentNullException(nameof(circuitHandlers));
            _logger          = logger ?? throw new ArgumentNullException(nameof(logger));

            Services = scope.ServiceProvider;

            Circuit = new Circuit(this);
            Handle  = new CircuitHandle()
            {
                CircuitHost = this,
            };

            Renderer.UnhandledException += Renderer_UnhandledException;
            Renderer.UnhandledSynchronizationException += SynchronizationContext_UnhandledException;
        }
示例#10
0
 private TestCircuitHost(CircuitId circuitId, AsyncServiceScope scope, CircuitOptions options, CircuitClientProxy client, RemoteRenderer renderer, IReadOnlyList <ComponentDescriptor> descriptors, RemoteJSRuntime jsRuntime, CircuitHandler[] circuitHandlers, ILogger logger)
     : base(circuitId, scope, options, client, renderer, descriptors, jsRuntime, circuitHandlers, logger)
 {
 }
示例#11
0
        public static async Task Connect(long qqId, string ip, ushort port, string authKey, Action <bool, string> ConnectedEvent)
        {
            try
            {
                // 一套能用的框架, 必须要注册至少一个 Invoker, Parser, Client 和 Handler
                // Invoker 负责消息调度
                // Parser 负责解析消息到具体接口以便调度器调用相关 Handler 下的处理方法
                // Client 负责收发原始数据
                IServiceProvider services = new ServiceCollection().AddMiraiBaseFramework() // 表示使用基于基础框架的构建器
                                            .Services
                                            .AddDefaultMiraiHttpFramework()                 // 表示使用 mirai-api-http 实现的构建器
                                            .AddInvoker <MiraiHttpMessageHandlerInvoker>()  // 使用默认的调度器
                                            .AddHandler <GroupMessage>()                    // 群消息
                                            .AddHandler <FriendMessage>()                   // 好友消息
                                            .AddHandler <TempMessage>()                     // 临时消息
                                            .AddClient <MiraiHttpSession>()                 // 使用默认的客户端
                                            .Services
                                                                                            // 由于 MiraiHttpSession 使用 IOptions<MiraiHttpSessionOptions>, 其作为 Singleton 被注册
                                                                                            // 配置此项将配置基于此 IServiceProvider 全局的连接配置
                                                                                            // 如果你想一个作用域一个配置的话
                                                                                            // 自行做一个实现类, 继承MiraiHttpSession, 构造参数中使用 IOptionsSnapshot<MiraiHttpSessionOptions>
                                                                                            // 并将其传递给父类的构造参数
                                                                                            // 然后在每一个作用域中!先!配置好 IOptionsSnapshot<MiraiHttpSessionOptions>, 再尝试获取 IMiraiHttpSession
                                            .Configure <MiraiHttpSessionOptions>(options =>
                {
                    options.Host    = ip;
                    options.Port    = port;                                                 // 端口
                    options.AuthKey = authKey;                                              // 凭据
                })
                                            .AddLogging()
                                            .BuildServiceProvider();
                await using AsyncServiceScope scope = services.CreateAsyncScope();             // 自 .NET 6.0 起才可以如此操作代替上边两句
                services = scope.ServiceProvider;
                IMiraiHttpSession session = services.GetRequiredService <IMiraiHttpSession>(); // 大部分服务都基于接口注册, 请使用接口作为类型解析

                await session.ConnectAsync(qqId);                                              // 填入期望连接到的机器人QQ号

                Cache.SetTaskAtFixedTime();

                IFriendInfo[] IFriendInfos = await session.GetFriendListAsync();

                string nickname = "未知";

                var self = IFriendInfos.Where(m => m.Id == qqId).FirstOrDefault();  //获取自身昵称失败, 部分QQ号好友中不存在自己?
                if (self != null)
                {
                    nickname = self.Name;
                }

                ConnectedEvent?.Invoke(true, nickname);

                BotInfo.QQId = session.QQNumber.Value;

                BotInfo.IsLogin = true;

                PluginManager.Connected(
                    BotInfo.QQId,
                    async(targetId, msg) => await session.SendFriendMessageAsync(targetId, await msg.ToMiraiApiHttpMessages(session, UploadTarget.Friend)),
                    async(targetId, msg) => await session.SendGroupMessageAsync(targetId, await msg.ToMiraiApiHttpMessages(session, UploadTarget.Group)),
                    async(targetId, targetGroup, msg) => await session.SendTempMessageAsync(targetId, targetGroup, await msg.ToMiraiApiHttpMessages(session, UploadTarget.Temp))
                    );

                RssWorker.StartRssTask(async(msgs, targetId, groupId) =>
                {
                    if (targetId != -1)
                    {
                        _ = session.SendFriendMessageAsync(targetId, await msgs.ToMiraiApiHttpMessages(session, UploadTarget.Friend));
                    }
                    else if (groupId != -1)
                    {
                        _ = session.SendGroupMessageAsync(groupId, await msgs.ToMiraiApiHttpMessages(session, UploadTarget.Group));
                    }
                });

                while (true)
                {
                    BotInfo.IsLogin = true;
                    if (Console.ReadLine() == "exit")
                    {
                        BotInfo.IsLogin = false;
                        PluginManager.Disconnected();
                        session.Dispose();
                        ConnectedEvent?.Invoke(false, "");
                        break;
                    }
                    Task.Delay(100).Wait();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog(ex);
                ConnectedEvent?.Invoke(false, ex.Message);
            }
        }