如何在SimpleIOC

时间:2016-02-23 19:44:14

标签: c# mvvm-light ioc-container

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

中注册

我认为这是它的方法:

SimpleIoc.Register<TClass> Method (Func<TClass>, String, Boolean)

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

这看起来像是一个ClassFactory。

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

cannot convert from <Class> to System.Func<Class>

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

有人可以举一个简短的例子来说明我是如何让这个工作的

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<ChatWindow>(cf.CreateChatWindow(ri), "key", true )
        var _messageWindow = new MessageWindow();
        _messageWindow.Show();
    }
}


class ChatMessage
{
    RosterItemX ri = new RosterItemX();
    ViewModelLocator.CreateWindow(ri);


}

1 个答案:

答案 0 :(得分:5)

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

的lambda即可

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