首页 > 解决方案 > 按名称获取服务

问题描述

我有一个 .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 语句?也许使用依赖注入是可能的,但我不太清楚该怎么做。或者有某种设计模式可以做到这一点。

标签: c#asp.net-coredependency-injectionswitch-statement

解决方案


你可以有一个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];
}

优点是这个解决方案是动态的,而不是像开关盒那样是静态的。这正是Open Closed 原则中的要点。

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


推荐阅读