如何在SimpleIOC中注册包含参数的类实例

我需要创建一个ViewModel实例,并在创建时将特定参数传递给ViewModel。 同时,此ViewModel实例应在SimpleIOC中注册

我认为这是它的方法:

SimpleIoc.Register Method (Func, String, Boolean) 

对于即时创建的最后一个参数,设置为true 。 因此,如果我理解正确,此方法需要引用将创建我的ViewModel实例的方法。

这看起来像一个ClassFactory。

我试着自己做,但我得到的只是

 cannot convert from  to System.Func 

所以它似乎总是传递类的实例,而不是应该创建它的方法。

有人能给出一个简短的例子,说明我是如何让这个工作的

 public class ClassFactory { public ChatWindow CreateChatWindow(RosterItemX ri) { return new ChatWindow(ri); } } public class ViewModelLocator { . . . . public static void CreateWindow(RosterItemX riv) { ClassFactory cf = new ClassFactory; SimpleIoc.Default.Register(cf.CreateChatWindow(ri), "key", true ) var _messageWindow = new MessageWindow(); _messageWindow.Show(); } } class ChatMessage { RosterItemX ri = new RosterItemX(); ViewModelLocator.CreateWindow(ri); } 

正如您自己所说,您正在为该函数提供ChatWindow的实例。 但是,它实际上需要一个创建ChatWindow的函数。 只需使用() =>将第一个参数转换为lambda即可

SimpleIoc.Default.Register(() => cf.CreateChatWindow(ri), "key", true);