lundi 17 avril 2017

Dependency injection : how do i resolve multiple instances at runtime?

I am using SimpleInjector for my injection fun.

As far as, I understand I only register and resolve with my container on my bootstrapper project.

So I have this code in my console application :

  static void Main(string[] args)
    {
        Container container = ComposeRoot();

        IBussinesLogicController controller = container.GetInstance<IBussinesLogicController>();
        controller.Execute();

        Console.WriteLine("Started");
        Console.ReadLine();
    }

    private static Container ComposeRoot()
    {
        var container = new Container();

        //Bussines Logic controllers.
        container.Register<IBussinesLogicController, BussinesLogicController>(Lifestyle.Singleton);
        container.Register<IStationController, StationController>(Lifestyle.Transient);

        //Data Access controllers.
        container.Register<IDataAccessController, DataAccessController>(Lifestyle.Singleton);
        container.Register<IDirectoryStructureController, DirectoryStructureController>(Lifestyle.Singleton);

        //Shared controllers.
        container.Register<ILogger, LoggerController>(Lifestyle.Singleton);

        container.Verify();

        return container;
    }

This will resolve my businesslogic controller and call Execute.

Now in execute I want to resolve 10 new instances of IStationController and add them to a list.

    List<IStationController> stations = new List<IStationController>();
        for (int i = 0; i < 10; i++)
        {
            //Resolve IStationController here...
            //IStationController station = diContainer.GetInstance<IStationController>();
            //station.StationName = $"Station {i}";
            //stations.Add(station);
        }

How do i do this since my BussinesLogic project does not and is not allowed a reference to the dependency container ?
I can resolve this easily by adding the dependency to the container but am afraid i am not folowing the correct patterns.

Please let me know what the right approach is to this problem.

Thanks!

Aucun commentaire:

Enregistrer un commentaire