Search code examples
dryioc

Registering and resolving dependencies in a loop


I have the following hardcoded setup in an application using MVVM:

var ips = configFile.Read();

for (string ip in ips)
{
    var tcpClient = new TcpClient(ip);
    var stream = (Stream) tcpClient.GetStream();
    var service = new Service(stream);
    var connectionViewModel = new ConnectionViewModel(service);
    var extendedViewModel = new ExtendedViewModel(connectionViewModel);
}

A number of IP addresses are read from a file, and each address results in a ViewModel being created that displays stuff from the IP.

What is the best approach if I want to let DryIoc handle this? All new objects are unique foreach loop.


Solution

  • Possible option is using Func to pass the ip:

    var c = new Container();
    c.Register<ExtendedViewModel>();
    c.Register<ConnectionViewModel>();
    c.Register<Service>();
    c.Register<TcpClient>();
    
    foreach (var ip in ips) {
        var getVM = c.Resolve<Func<string, ExtendedViewModel>>();
        var vm = getVM(ip);
        // use vm
    }
    

    Update:

    For Stream, add the following registration without changing the resolution part:

    c.Register<Stream>(Made.Of(
        _ => ServiceInfo.Of<TcpClient>(),
        tcpClient => (Stream)tcpClient.GetStream()));
    

    Made.Of plays nicely with Func and other wrappers resolutions, and can be in the middle of object graph. That's why it is preferable over RegisterDelegate.