Artavazd
Artavazd

Reputation: 175

Get Service by Name

I have a .Net Core gaming project. In any API, I want to get the game-specific service by giving the game name to it (or Id). I currently have it as follows:

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

Let's say we have much more game service, I have only listed a few but you get the idea. Is there a better way to get the service instead of using the switch statement? Maybe it's possible using dependency injection but I don't quite know how to do it. Or there is some kind of design pattern to do so.

Upvotes: 1

Views: 692

Answers (1)

Ygalbel
Ygalbel

Reputation: 5519

You can have a Dictionary of GameNames, Func<GameServiceBase>.

It will be like this:

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

The pros is that this solution is dynamic and not static as is in a switch case. That exactly the point in Open Closed principle.

I used a func of GameSericeBase because it's exactly as in the question, the function return a new instance in every call.

Upvotes: 1

Related Questions