1

I am developing a small game in a console application in .NET Core where the the start of the application is StartPlay method of IGamePlay interface. I have a class GamePlay which implements this interface.

interface IGamePlay
{
    void StartPlay(List<Person> ListOfPlayers, int deckSize);
    void PlayFromShuffledCards(List<Person> ListOfPlayers, Stack<Card> shuffledCards);

    void PlayFromDiscardCards(List<Person> ListOfPlayers);
}

In my main method I have the following code:

class Program
{
    static void Main(string[] args)
    {
        var serviceProvider = new ServiceCollection()               
               .AddSingleton<IGamePlay,GamePlay>()                
               .AddSingleton<GamePlay>()
               .BuildServiceProvider();

        // Populate listof players
        var gamePlay = serviceProvider.GetRequiredService<GamePlay>();

        gamePlay.StartPlay(listOfPlayers,deckSize);
    }
}

From my main method, I am directly calling StartPlay of the gamePlay class in the last line of the main method.

Is this a violation of DI principles? If yes, what is the best way to instantiate it from main?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
VA1267
  • 311
  • 1
  • 8
  • 4
    No, it is not violating any principles. `Main` method is entry point of the application and is correct place where you can setup your dependencies and call "main" application object. Similar to `application.Run()` ;) – Fabio Nov 24 '21 at 06:27
  • 2
    I just wanna add to @Fabio's excellent comment. This is called Composition Root (CR), where objects are being composed. – Refael Sheinker Nov 24 '21 at 09:10
  • 1
    If you want to learn more about the concept of the Composition Root, you can read [this article](https://freecontent.manning.com/dependency-injection-in-net-2nd-edition-understanding-the-composition-root/). – Steven Nov 25 '21 at 14:53

0 Answers0