-->

How to register a class instance including a param

2020-08-01 05:52发布

问题:

I need to create an instance of a ViewModel with a specific parameter passed to the ViewModel when created. At the same time this ViewModel instance should be registered in SimpleIOC

i thought this was the method for it:

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

with set to true for the last parameter for instant creation. so if i understood that correctly, this method wants a reference to a method that will create my ViewModel instance.

This is called a ClassFactory as it seems.

i tried to do it myself but all i get is

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

so as it seems im passing always the instance of the class, and not the method that should create it.

can someone give a short example how i can get this to work

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:

As you yourself said you are giving an instance of a ChatWindow to the function. However, it actually expects a function that creates a ChatWindow. Just convert the first parameter to a lambda with () =>

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