rabbitmq 从静态工厂类访问ASP.NET核心DI容器

kcwpcxri  于 2023-02-04  发布在  RabbitMQ
关注(0)|答案(7)|浏览(139)

我已经创建了一个ASP.NET核心MVC/WebApi站点,它有一个基于JamesStill的博客文章Real-World PubSub Messaging with RabbitMQ的RabbitMQ订阅者。
在他的文章中,他使用了一个静态类来启动队列订阅者并定义队列事件的事件处理程序,然后这个静态方法通过一个静态工厂类示例化事件处理程序类。

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;

namespace NST.Web.MessageProcessing
{
    public static class MessageListener
    {
        private static IConnection _connection;
        private static IModel _channel;

        public static void Start(string hostName, string userName, string password, int port)
        {
            var factory = new ConnectionFactory
            {
                HostName = hostName,
                Port = port,
                UserName = userName,
                Password = password,
                VirtualHost = "/",
                AutomaticRecoveryEnabled = true,
                NetworkRecoveryInterval = TimeSpan.FromSeconds(15)
            };

            _connection = factory.CreateConnection();
            _channel = _connection.CreateModel();
            _channel.ExchangeDeclare(exchange: "myExchange", type: "direct", durable: true);

            var queueName = "myQueue";

            QueueDeclareOk ok = _channel.QueueDeclare(queueName, true, false, false, null);

            _channel.QueueBind(queue: queueName, exchange: "myExchange", routingKey: "myRoutingKey");

            var consumer = new EventingBasicConsumer(_channel);
            consumer.Received += ConsumerOnReceived;

            _channel.BasicConsume(queue: queueName, noAck: false, consumer: consumer);

        }

        public static void Stop()
        {
            _channel.Close(200, "Goodbye");
            _connection.Close();
        }

        private static void ConsumerOnReceived(object sender, BasicDeliverEventArgs ea)
        {
            // get the details from the event
            var body = ea.Body;
            var message = Encoding.UTF8.GetString(body);
            var messageType = "endpoint";  // hardcoding the message type while we dev...

            // instantiate the appropriate handler based on the message type
            IMessageProcessor processor = MessageHandlerFactory.Create(messageType);
            processor.Process(message);

            // Ack the event on the queue
            IBasicConsumer consumer = (IBasicConsumer)sender;
            consumer.Model.BasicAck(ea.DeliveryTag, false);
        }

    }
}

在我现在需要在消息处理器工厂中解析服务而不仅仅是写入控制台之前,它一直工作得很好。

using NST.Web.Services;
using System;

namespace NST.Web.MessageProcessing
{
    public static class MessageHandlerFactory
    {
        public static IMessageProcessor Create(string messageType)
        {
            switch (messageType.ToLower())
            {
                case "ipset":
                    // need to resolve IIpSetService here...
                    IIpSetService ipService = ???????

                    return new IpSetMessageProcessor(ipService);

                case "endpoint":
                    // need to resolve IEndpointService here...
                    IEndpointService epService = ???????

                    // create new message processor
                    return new EndpointMessageProcessor(epService);

                default:
                    throw new Exception("Unknown message type");
            }
        }
    }
}

有没有什么方法可以访问ASP.NET核心IoC容器来解决依赖项?我真的不想手动旋转整个依赖项堆栈:(
或者,是否有更好的方法从ASP.NET核心应用程序订阅RabbitMQ?我找到了RestBus,但它没有针对Core1.x进行更新

wwtsj6pe

wwtsj6pe1#

您可以避免使用静态类,并始终使用依赖注入,同时结合使用:

  • 每当应用程序启动/停止时,使用IApplicationLifetime启动/停止侦听器。
  • 使用IServiceProvider创建消息处理器的示例。

首先,让我们将配置移到它自己的类中,该类可以从appsettings.json中填充:

public class RabbitOptions
{
    public string HostName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public int Port { get; set; }
}

// In appsettings.json:
{
  "Rabbit": {
    "hostName": "192.168.99.100",
    "username": "guest",
    "password": "guest",
    "port": 5672
  }
}

接下来,将MessageHandlerFactory转换为一个非静态类,该类接收一个IServiceProvider作为依赖项,它将使用服务提供程序来解析消息处理器示例:

public class MessageHandlerFactory
{
    private readonly IServiceProvider services;
    public MessageHandlerFactory(IServiceProvider services)
    {
        this.services = services;
    }

    public IMessageProcessor Create(string messageType)
    {
        switch (messageType.ToLower())
        {
            case "ipset":
                return services.GetService<IpSetMessageProcessor>();                
            case "endpoint":
                return services.GetService<EndpointMessageProcessor>();
            default:
                throw new Exception("Unknown message type");
        }
    }
}

通过这种方式,消息处理器类可以在构造函数中接收它们需要的任何依赖项(只要在Startup.ConfigureServices中配置它们)。例如,我将一个ILogger注入到我的一个示例处理器中:

public class IpSetMessageProcessor : IMessageProcessor
{
    private ILogger<IpSetMessageProcessor> logger;
    public IpSetMessageProcessor(ILogger<IpSetMessageProcessor> logger)
    {
        this.logger = logger;
    }

    public void Process(string message)
    {
        logger.LogInformation("Received message: {0}", message);
    }
}

现在把MessageListener转换成一个依赖于IOptions<RabbitOptions>MessageHandlerFactory的非静态类,它和你原来的类非常相似,我只是用选项依赖替换了Start方法的参数,处理器工厂现在是一个依赖而不是静态类:

public class MessageListener
{
    private readonly RabbitOptions opts;
    private readonly MessageHandlerFactory handlerFactory;
    private IConnection _connection;
    private IModel _channel;

    public MessageListener(IOptions<RabbitOptions> opts, MessageHandlerFactory handlerFactory)
    {
        this.opts = opts.Value;
        this.handlerFactory = handlerFactory;
    }

    public void Start()
    {
        var factory = new ConnectionFactory
        {
            HostName = opts.HostName,
            Port = opts.Port,
            UserName = opts.UserName,
            Password = opts.Password,
            VirtualHost = "/",
            AutomaticRecoveryEnabled = true,
            NetworkRecoveryInterval = TimeSpan.FromSeconds(15)
        };

        _connection = factory.CreateConnection();
        _channel = _connection.CreateModel();
        _channel.ExchangeDeclare(exchange: "myExchange", type: "direct", durable: true);

        var queueName = "myQueue";

        QueueDeclareOk ok = _channel.QueueDeclare(queueName, true, false, false, null);

        _channel.QueueBind(queue: queueName, exchange: "myExchange", routingKey: "myRoutingKey");

        var consumer = new EventingBasicConsumer(_channel);
        consumer.Received += ConsumerOnReceived;

        _channel.BasicConsume(queue: queueName, noAck: false, consumer: consumer);

    }

    public void Stop()
    {
        _channel.Close(200, "Goodbye");
        _connection.Close();
    }

    private void ConsumerOnReceived(object sender, BasicDeliverEventArgs ea)
    {
        // get the details from the event
        var body = ea.Body;
        var message = Encoding.UTF8.GetString(body);
        var messageType = "endpoint";  // hardcoding the message type while we dev...
        //var messageType = Encoding.UTF8.GetString(ea.BasicProperties.Headers["message-type"] as byte[]);

        // instantiate the appropriate handler based on the message type
        IMessageProcessor processor = handlerFactory.Create(messageType);
        processor.Process(message);

        // Ack the event on the queue
        IBasicConsumer consumer = (IBasicConsumer)sender;
        consumer.Model.BasicAck(ea.DeliveryTag, false);
    }
}

到了这里,您需要更新Startup.ConfigureServices方法,使它知道您的服务和选项(如果需要,可以为侦听器和处理程序工厂创建接口):

public void ConfigureServices(IServiceCollection services)
{            
    // ...

    // Add RabbitMQ services
    services.Configure<RabbitOptions>(Configuration.GetSection("rabbit"));
    services.AddTransient<MessageListener>();
    services.AddTransient<MessageHandlerFactory>();
    services.AddTransient<IpSetMessageProcessor>();
    services.AddTransient<EndpointMessageProcessor>();
}

最后,更新Startup.Configure方法,以获取额外的IApplicationLifetime参数,并在ApplicationStarted/ApplicationStopped事件中启动/停止消息侦听器(尽管我不久前注意到使用IISExpress的ApplicationStopping事件存在一些问题,如在this question中):

public MessageListener MessageListener { get; private set; }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
{
    appLifetime.ApplicationStarted.Register(() =>
    {
        MessageListener = app.ApplicationServices.GetService<MessageListener>();
        MessageListener.Start();
    });
    appLifetime.ApplicationStopping.Register(() =>
    {
        MessageListener.Stop();
    });

    // ...
}
monwx1rj

monwx1rj2#

尽管使用依赖注入是一个更好的解决方案,但在某些情况下,您必须使用静态方法(如扩展方法)。
对于这些情况,您可以向静态类添加静态属性,并在ConfigureServices方法中初始化它。
例如:

public static class EnumExtentions
{
    static public IStringLocalizerFactory StringLocalizerFactory { set; get; }

    public static string GetDisplayName(this Enum e)
    {
        var resourceManager = StringLocalizerFactory.Create(e.GetType());
        var key = e.ToString();
        var resourceDisplayName = resourceManager.GetString(key);

        return resourceDisplayName;
    }
}

和配置服务中:

EnumExtentions.StringLocalizerFactory = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
f87krz0w

f87krz0w3#

我知道我的回答晚了,但我想分享我是如何做到的。

首先:使用ServiceLocatorAntipattern,所以尽量不要使用它。在我的例子中,我需要它在我的DomainModel中调用MediatR来实现DomainEvents逻辑。
然而,我必须找到一种方法来调用DomainModel中的静态类,以从DI获取某个注册服务的示例。

因此,我决定使用HttpContext来访问IServiceProvider,但我需要从静态方法访问它,而不在域模型中提及它。
我们开始吧:
1-我创建了一个接口来 Package IServiceProvider

public interface IServiceProviderProxy
{
    T GetService<T>();
    IEnumerable<T> GetServices<T>();
    object GetService(Type type);
    IEnumerable<object> GetServices(Type type);
}

2-然后,我创建了一个静态类作为ServiceLocator访问点

public static class ServiceLocator
{
    private static IServiceProviderProxy diProxy;

    public static IServiceProviderProxy ServiceProvider => diProxy ?? throw new Exception("You should Initialize the ServiceProvider before using it.");

    public static void Initialize(IServiceProviderProxy proxy)
    {
        diProxy = proxy;
    }
}

3-我创建了IServiceProviderProxy的实现,它在内部使用IHttpContextAccessor

public class HttpContextServiceProviderProxy : IServiceProviderProxy
{
    private readonly IHttpContextAccessor contextAccessor;

    public HttpContextServiceProviderProxy(IHttpContextAccessor contextAccessor)
    {
        this.contextAccessor = contextAccessor;
    }

    public T GetService<T>()
    {
        return contextAccessor.HttpContext.RequestServices.GetService<T>();
    }

    public IEnumerable<T> GetServices<T>()
    {
        return contextAccessor.HttpContext.RequestServices.GetServices<T>();
    }

    public object GetService(Type type)
    {
        return contextAccessor.HttpContext.RequestServices.GetService(type);
    }

    public IEnumerable<object> GetServices(Type type)
    {
        return contextAccessor.HttpContext.RequestServices.GetServices(type);
    }
}

4-我应该像这样在DI中注册IServiceProviderProxy

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    services.AddSingleton<IServiceProviderProxy, HttpContextServiceProviderProxy>();
    .......
}

5-最后一步是在应用程序启动时使用IServiceProviderProxy示例初始化ServiceLocator

public void Configure(IApplicationBuilder app, IHostingEnvironment env,IServiceProvider sp)
{
    ServiceLocator.Initialize(sp.GetService<IServiceProviderProxy>());
}

因此,现在您可以在DomainModel类中调用ServiceLocator“Or and needed place”并解析所需的依赖项。

public class FakeModel
{
    public FakeModel(Guid id, string value)
    {
        Id = id;
        Value = value;
    }

    public Guid Id { get; }
    public string Value { get; private set; }

    public async Task UpdateAsync(string value)
    {
        Value = value;
        var mediator = ServiceLocator.ServiceProvider.GetService<IMediator>();
        await mediator.Send(new FakeModelUpdated(this));
    }
}
fcg9iug3

fcg9iug34#

以下是我对你的情况的看法:
如果可能,我将发送解析的服务作为参数

public static IMessageProcessor Create(string messageType, IIpSetService ipService)
{
    //
}

否则使用寿命将很重要。

如果服务是单例的,我只需要设置configure方法的依赖关系:

// configure method
public IApplicationBuilder Configure(IApplicationBuilder app)
{
    var ipService = app.ApplicationServices.GetService<IIpSetService>();
    MessageHandlerFactory.IIpSetService = ipService;
}

// static class
public static IIpSetService IpSetService;

public static IMessageProcessor Create(string messageType)
{
    // use IpSetService
}

如果服务生存期是有范围的,我将使用HttpContextAccessor:

//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

public IApplicationBuilder Configure(IApplicationBuilder app)
{
    var httpContextAccessor= app.ApplicationServices.GetService<IHttpContextAccessor>();
    MessageHandlerFactory.HttpContextAccessor = httpContextAccessor;
}

// static class
public static IHttpContextAccessor HttpContextAccessor;

public static IMessageProcessor Create(string messageType)
{
    var ipSetService = HttpContextAccessor.HttpContext.RequestServices.GetService<IIpSetService>();
    // use it
}
insrf1ej

insrf1ej5#

Here是ServiceLocator的一个很好的实现,它也使用了作用域,甚至可以用于IHttpContextAccessor!
只需将this class复制到代码中,然后注册ServiceLocator

ServiceActivator.Configure(app.ApplicationServices);

**重要说明 :ServiceLocator被视为反模式,因此如果您有任何其他选择,请不要使用它!!!!

polkgigr

polkgigr6#

关于瓦希德·比塔尔的答复
太神奇了!对于.Net Core 6,我在Program.cs上做了:

builder.Services.AddSingleton<IServiceProviderProxy, HttpContextServiceProviderProxy>();

ServiceLocator.Initialize(app.Services.GetService<IServiceProviderProxy>());
b1payxdu

b1payxdu7#

您可以在Configure中获得服务引用:

app.UseMvc();
var myServiceRef = app.ApplicationServices.GetService<MyService>();

然后将其传递给init函数或在类上设置静态成员
当然,正如其他答案中所解释的,依赖注入将是一个更好的解决方案...

相关问题