Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IoC - Constructor takes a runtime value as one parameter and a service as another

I have a WPF app which, when it starts, looks at the file system for some config files

For each config file it finds, it displays some info in a different window

Each window has an associated ViewModel object which is bound to the windows datacontext

So a new ViewModel is created for each config file. An object representing the data in the config file is passed into the viewmodels constructor

However, the View model also has other dependancies passed into the constructor

The code looks something like this (in a bootstrapper initiated from app.xaml)

foreach (WindowConfig config in ConfigManager.GetConfigs())
{
    IMyService svc = new MyService();

    //change to resolve from IoC container
    MyViewModel vm = new MyViewModel(config, svc);

    Window1 view = new Window1();

    view.DataContext = vm;

    window.show();
}

I want to use Castle IoC contaoiner resolve these dependancies. I know how to do that for IMyService, but how can I do it for the specific class that has been created from the config file ?

thanks

like image 563
ChrisCa Avatar asked Mar 22 '11 21:03

ChrisCa


1 Answers

Always remember that in the application code, pulling from the container is never the solution. Application code should be unaware that there's a DI container in play.

The general solution when you need to resolve a dependency based on a run-time value is to use an Abstract Factory.

In your case, the factory might look like this (assuming that your config variables are strings:

public interface IViewModelFactory
{
    IViewModel Create(string configuration);
}

Now you can inject the IViewModelFactory as a single dependency into the class that loops through the configuration files.

To implement IViewModelFactory you can either do it by hand or use Castle Windsor's Typed Factory Facility to implement it for you.

like image 169
Mark Seemann Avatar answered Sep 23 '22 03:09

Mark Seemann