Accessing ASP.NET Core DI Container From Static Factory Class

后端 未结 5 1608
闹比i
闹比i 2021-01-30 16:57

I\'ve created an ASP.NET Core MVC/WebApi site that has a RabbitMQ subscriber based off James Still\'s blog article Real-World PubSub Messaging with RabbitMQ.

In his arti

5条回答
  •  一整个雨季
    2021-01-30 17:26

    Here is my opinion about your case:

    If possible i would send resolved service as a parameter

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

    Otherwise service lifetime would be important.

    If service is singleton i would just set dependency on configure method:

     // configure method
    public IApplicationBuilder Configure(IApplicationBuilder app)
    {
        var ipService = app.ApplicationServices.GetService();
        MessageHandlerFactory.IIpSetService = ipService;
    }
    
    // static class
    public static IIpSetService IpSetService;
    
    public static IMessageProcessor Create(string messageType)
    {
        // use IpSetService
    }
    

    If service lifetime is scoped i would use HttpContextAccessor:

    //Startup.cs
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton();
    }
    
    public IApplicationBuilder Configure(IApplicationBuilder app)
    {
        var httpContextAccessor= app.ApplicationServices.GetService();
        MessageHandlerFactory.HttpContextAccessor = httpContextAccessor;
    }
    
    // static class
    public static IHttpContextAccessor HttpContextAccessor;
    
    public static IMessageProcessor Create(string messageType)
    {
        var ipSetService = HttpContextAccessor.HttpContext.RequestServices.GetService();
        // use it
    }
    

提交回复
热议问题