我需要创建一个 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);
}
最佳答案
正如您自己所说,您正在提供一个 ChatWindow
的实例到功能。但是,它实际上需要一个创建 ChatWindow
的函数。 .只需使用 () =>
将第一个参数转换为 lambda。
SimpleIoc.Default.Register<ChatWindow>(() => cf.CreateChatWindow(ri), "key", true);
关于c# - 如何在 SimpleIOC 中注册包含参数的类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35586715/