• Welcome to the world's largest Chinese hacker forum

    Welcome to the world's largest Chinese hacker forum, our forum registration is open! You can now register for technical communication with us, this is a free and open to the world of the BBS, we founded the purpose for the study of network security, please don't release business of black/grey, or on the BBS posts, to seek help hacker if violations, we will permanently frozen your IP and account, thank you for your cooperation. Hacker attack and defense cracking or network Security

    business please click here: Creation Security  From CNHACKTEAM

Recommended Posts

这篇文章参考网上的教程,主要解决了EasyNetQ的依赖注入服务问题。

主要涉及四个文件:

ApplicationExtenssion.cs.Net中间件的实现

订单消费者。铯消息消费者的实现

WindsorMessageDispatcher.cs通过容器解析获得消费者服务

Startup.cs相关服务的注册及中间件引用

主要参考代码:

ApplicationExtenssion.cs

公共静态类应用程序扩展

{

///摘要

///中间件实现

////摘要

///param name=' app builder '/param

///param name='订阅id前缀'/param

///param name='assembly'/param

///返回/返回

公共静态IApplicationBuilder使用订阅(此IApplicationBuilder appBuilder,string subscriptionIdPrefix,Assembly assembly)

{

定义变量服务=appBuilder .应用服务。创建范围().服务提供商;

定义变量生命周期=服务GetServiceIHostApplicationLifetime();

var总线=服务GetRequiredServiceIBus();

一生应用程序已启动。注册(()=

{

var subscriber=新自动订户(总线,订阅id前缀);

//需要指定AutoSubscriberMessageDispatcher对应的实例

//并可以通过构造函数传参,如:IServicesProvider,即:服务

订户AutoSubscriberMessageDispatcher=新的WindsorMessageDispatcher(服务);

订户订阅(新程序集[] {程序集});

订户SubscribeAsync(新程序集[] {程序集});

});

一生。应用程序已停止。寄存器(()={ bus .dispose();});

返回appBuilder

}

}

订单消费者。铯

///摘要

///IConsume接口的实现类

////摘要

公共类订单消费者:图标消费信息

{

私有只读ILoggerOrderConsumer记录器;

///摘要

///可以注入相关服务

////摘要

///param name='logger'/param

公共订单消费者(ILoggerOrderConsumer记录器)

{

this.logger=logger

}

///摘要

///消息的消费方法

////摘要

/// <param name="message"></param> /// <param name="cancellationToken"></param> public void Consume(MessageDto message, CancellationToken cancellationToken = default) { logger.LogInformation(JsonConvert.SerializeObject(message)); } }

WindsorMessageDispatcher.cs

    /// <summary>
    /// 结合官方教程实现自动订阅消息转发
    /// </summary>
    public class WindsorMessageDispatcher : IAutoSubscriberMessageDispatcher
    {
        private readonly IServiceProvider service;
        /// <summary>
        /// 参数由中间件的AutoSubscriberMessageDispatcher进行传递
        /// </summary>
        /// <param name="service"></param>
        public WindsorMessageDispatcher(IServiceProvider service)
        {
            this.service = service;
        }
        /// <summary>
        /// 同步方法,可以解析TConsumer对应的服务
        /// </summary>
        /// <typeparam name="TMessage"></typeparam>
        /// <typeparam name="TConsumer"></typeparam>
        /// <param name="message"></param>
        /// <param name="cancellationToken"></param>
        void IAutoSubscriberMessageDispatcher.Dispatch<TMessage, TConsumer>(TMessage message, CancellationToken cancellationToken)
        {
            //通过容器获取对应的消费者服务,也可以通过Autofac实现
            var consumer = service.GetService<IConsume<MessageDto>>();
            //通过解析到的服务调用对应的消费者实现的方法
            consumer.Consume(message as MessageDto, cancellationToken);
        }
        /// <summary>
        /// 异步方法
        /// </summary>
        /// <typeparam name="TMessage"></typeparam>
        /// <typeparam name="TConsumer"></typeparam>
        /// <param name="message"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        async Task IAutoSubscriberMessageDispatcher.DispatchAsync<TMessage, TConsumer>(TMessage message, CancellationToken cancellationToken)
        {
            var consumer = service.GetService<TConsumer>();
            await consumer.ConsumeAsync(message, cancellationToken);
        }
    }

Startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            string rabbitMqConnection = Configuration["RabbitMqConnection"];
            //注册IBus为单例模式
            services.AddSingleton(RabbitHutch.CreateBus(rabbitMqConnection));
            //注册IConsume的实现类,EasyNetQ会自动扫描实现该接口的类
            services.AddSingleton<IConsume<MessageDto>,OrderConsumer>();
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "EasyNetQ.WebApi", Version = "v1" });
            });
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "EasyNetQ.WebApi v1"));
            }
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            //添加相应的中间件
            app.UseSubscribe("OrderService", Assembly.GetExecutingAssembly());
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now