Untitled

 avatar
unknown
plain_text
2 years ago
2.9 kB
7
Indexable
To apply the Dependency Injection (DI) pattern to your code, you can use a DI container or manually wire up the dependencies. Here's an example of how you can modify your code to use DI using .NET Core's built-in DI container:

First, you'll need to define the interfaces and their implementations:

csharp
Copy code
// IGoalGenerator interface remains the same

interface IGuessChecker
{
    string Check(string goal, string guess);
}

class GuessChecker : IGuessChecker
{
    // Implementation of IGuessChecker remains the same
}

interface IPlayerDataStorage
{
    void Write(string name, int guesses);
    void ShowTopList();
}

class PlayerDataStorage : IPlayerDataStorage
{
    // Implementation of IPlayerDataStorage remains the same
}

// IGoalGeneratorFactory interface remains the same

interface IGame
{
    void Play();
}

class MainClass : IGame
{
    private readonly IGoalGeneratorFactory goalGeneratorFactory;
    private readonly IGuessChecker guessChecker;
    private readonly IPlayerDataStorage playerDataStorage;

    public MainClass(IGoalGeneratorFactory generatorFactory, IGuessChecker checker, IPlayerDataStorage storage)
    {
        goalGeneratorFactory = generatorFactory;
        guessChecker = checker;
        playerDataStorage = storage;
    }

    // Implementation of Play method remains the same
}
Next, modify your Program class to use DI and configure the DI container:

csharp
Copy code
using Microsoft.Extensions.DependencyInjection;
using LaborationCC.Classes;
using LaborationCC.Interfaces;

namespace LaborationCC
{
    class Program
    {
        static void Main(string[] args)
        {
            string resultFilePath = "result.txt";

            // Create a new instance of the DI container
            var serviceProvider = new ServiceCollection()
                .AddSingleton<IGoalGeneratorFactory, RandomGoalGeneratorFactory>()
                .AddSingleton<IGuessChecker, GuessChecker>()
                .AddSingleton<IPlayerDataStorage>(new PlayerDataStorage(resultFilePath))
                .AddSingleton<IGame, MainClass>()
                .BuildServiceProvider();

            // Resolve the game instance from the DI container
            var game = serviceProvider.GetService<IGame>();

            game.Play();
        }
    }
}
In this example, the DI container is used to register the implementations of the interfaces (RandomGoalGeneratorFactory, GuessChecker, PlayerDataStorage, and MainClass). The ServiceProvider is then used to resolve the IGame instance, which in turn resolves its dependencies (IGoalGeneratorFactory, IGuessChecker, and IPlayerDataStorage) from the container.

With DI in place, the dependencies are injected into the MainClass constructor, making it easier to manage and swap implementations if needed.
Editor is loading...