Accessing ASP.NET Core DI Container From Static Factory Class

后端 未结 5 1606
闹比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:34

    Even though using Dependency Injection is a better solution, but in some cases you have to use static methods (like in Extension Methods).

    For those cases you can add a static property to your static class and initialize it in your ConfigureServices method.

    For example:

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

    and in your ConfigureServices:

    EnumExtentions.StringLocalizerFactory = services.BuildServiceProvider().GetService();
    

提交回复
热议问题