Registering and resolving dependencies in a loop

时间:2016-06-10 16:16:10

标签: dryioc

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.

1 个答案:

答案 0 :(得分:1)

可能的选择是使用Func传递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
}

<强>更新

对于Stream,添加以下注册而不更改分辨率部分:

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

Made.Of与Func和其他包装器分辨率很好地配合,并且可以在对象图的中间。这就是为什么它优于RegisterDelegate。