如何在SimpleIOC中注册包含参数的类实例 [英] How to register a class instance including a parameter in SimpleIOC
问题描述
我需要创建一个ViewModel实例,并在创建时将特定参数传递给ViewModel.同时,此ViewModel实例应在SimpleIOC中注册
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)
的最后一个参数设置为true
,以便立即创建.
因此,如果我正确理解,则此方法希望引用将创建我的ViewModel实例的方法.
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.
这看起来像是ClassFactory.
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);
}
推荐答案
正如您自己所说,您正在为函数提供ChatWindow
的实例.但是,它实际上期望一个创建ChatWindow
的函数.只需使用() =>
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);
这篇关于如何在SimpleIOC中注册包含参数的类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!