从静态工厂类访问ASP.NET Core DI容器

Nic*_*ick 29 c# dependency-injection rabbitmq service-locator asp.net-core

我创建了一个ASP.NET Core MVC/WebApi站点,该站点有一个RabbitMQ订阅者,基于James Still的博客文章Real-World PubSub Messaging with 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);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

它工作得很好,我现在需要在消息处理器工厂中解析服务,而不是只写入控制台.

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");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法访问ASP.NET Core IoC容器来解决依赖关系?我真的不想手动旋转整个依赖堆栈:(

或者,有没有更好的方法从ASP.NET Core应用程序订阅RabbitMQ?我找到了RestBus,但它没有针对Core 1.x进行更新

Dan*_*.G. 27

您可以避免使用静态类并一直使用依赖注入:

  • 用于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
  }
}
Run Code Online (Sandbox Code Playgroud)

接下来,转换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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,您的消息处理器类可以在构造函数中接收它们所需的任何依赖项(只要您配置它们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);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在转换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);
    }
}
Run Code Online (Sandbox Code Playgroud)

几乎在那里,您将需要更新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>();
}
Run Code Online (Sandbox Code Playgroud)

最后,更新Startup.Configure方法以获取额外的IApplicationLifetime参数并在ApplicationStarted/ ApplicationStoppedevents中启动/停止消息监听器(虽然我之前注意到使用IISExpress的ApplicationStopping事件的一些问题,如本问题所示):

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();
    });

    // ...
}
Run Code Online (Sandbox Code Playgroud)


Ham*_*edH 17

尽管使用依赖注入是一种更好的解决方案,但在某些情况下,您必须使用静态方法(如扩展方法).

对于这些情况,您可以向静态类添加静态属性,并在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的ConfigureServices中:

EnumExtentions.StringLocalizerFactory = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
Run Code Online (Sandbox Code Playgroud)

  • 这是将扩展方法与容器中的单例一起使用的实用解决方案。注意:在`Configure()`中设置静态对象,而不是在`ConfigureServices()`中(无论如何对于.Net Core 3+)。例如“public voidConfigure(IApplicationBuilder应用程序,IStringLocalizerFactory工厂)” (2认同)

Wah*_*tar 12

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

首先:使用ServiceLocator反模式,所以尽量不要使用它。在我来说,我需要它来打电话MediatR我的DomainModel内实现DomainEvents逻辑。

但是,我必须找到一种方法来调用我的 DomainModel 中的静态类,以从 DI 获取某些已注册服务的实例。

所以我决定使用HttpContext来访问 ,IServiceProvider但我需要从静态方法访问它,而不在我的域模型中提及它。

我们开始做吧:

1-我创建了一个接口来包装 IServiceProvider

public interface IServiceProviderProxy
{
    T GetService<T>();
    IEnumerable<T> GetServices<T>();
    object GetService(Type type);
    IEnumerable<object> GetServices(Type type);
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    services.AddSingleton<IServiceProviderProxy, HttpContextServiceProviderProxy>();
    .......
}
Run Code Online (Sandbox Code Playgroud)

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

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

因此,现在您可以在您的 DomainModel 类“或和需要的地方”中调用 ServiceLocator 并解析您需要的依赖项。

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你!这正是我正在尝试做的,因为我想从我的域内向 Mediatr 引发事件。 (2认同)

ade*_*lin 5

以下是我对你的案例的看法:

如果可能的话,我会发送已解决的服务作为参数

public static IMessageProcessor Create(string messageType, IIpSetService ipService)
{
    //
}
Run Code Online (Sandbox Code Playgroud)

否则使用寿命将很重要。

如果服务是单例的,我只需设置对配置方法的依赖:

 // 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
}
Run Code Online (Sandbox Code Playgroud)

如果服务生命周期是有范围的,我将使用 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
}
Run Code Online (Sandbox Code Playgroud)

  • 投了赞成票。但为什么不直接使用 httpcontextaccessor 而不管它是作用域还是单例呢?在单例中使用它有危险吗? (2认同)