【问题标题】:Get Service by Name按名称获取服务
【发布时间】:2020-09-15 11:29:48
【问题描述】:

我有一个 .Net Core 游戏项目。在任何 API 中,我都想通过为其提供游戏名称(或 Id)来获得特定于游戏的服务。我目前有如下:

public GameServiceBase GetGameService(string gameName)
{
         switch (gameName)
         {
                case GameNames.Keno:
                    return new KenoService();
                case GameNames.BetOnPoker:
                    return new BetOnPokerService();
                case GameNames.Minesweeper:
                    return new MinesweeperService();
                default:
                    throw new Exception();
        }
}

假设我们有更多的游戏服务,我只列出了一些,但你明白了。有没有更好的方法来获取服务而不是使用 switch 语句?也许使用依赖注入是可能的,但我不太清楚该怎么做。或者有某种设计模式可以做到这一点。

【问题讨论】:

  • 对于初学者,您可以使用Dictionary<string, GameService>(假设您的所有游戏服务都实现了接口 GameService)

标签: c# asp.net-core dependency-injection switch-statement


【解决方案1】:

您可以拥有DictionaryGameNames, Func<GameServiceBase>

会是这样的:

static Dictionary<GameNames,Func<GameServiceBase>>  dict = new Dictionary<GameNames,Func<GameServiceBase>>();

// can be in object creation
dict.Add(GameNames.Keno, () => new KenoService());
.
.
public GameServiceBase GetGameService(string gameName) 
{
    // handle here case of wrong game name
...

    return dict[gameName];
}

优点是这个解决方案是动态的,而不是像 switch case 那样是静态的。 这正是Open Closed principle 中的重点。

我使用了 GameSericeBase 的函数,因为它与问题中的完全一样,该函数在每次调用时都会返回一个新实例。

【讨论】:

  • 你的意思是使用 IGameServiceBase 作为 Func 中的类型吗?
  • 是函数的返回参数。在您的问题代码中,您在每次调用中都返回一个新实例。所以 Func 会给你同样的行为。
猜你喜欢
  • 2014-05-15
  • 2014-02-16
  • 2014-08-10
  • 2011-11-04
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 2018-08-14
相关资源
最近更新 更多