在MVVMLight的SimpleIoc中注册已经实例化的类

时间:2012-04-10 13:47:02

标签: silverlight dependency-injection inversion-of-control mvvm-light

我正在使用SimpleIoc for Dependency Injection来使用Static类。 SimpleIoc中有一个Register<TClass>(Func<TClass> factory) where TClass : class方法,但我找不到任何使用它的示例。这是一个链接to the source code

我是否正确接近这个,或者DI总是需要在注册时创建吗?这是我应该用来注册课程的方法吗? 你能给我一个如何做到这一点的例子吗?

这是我正在尝试更新的Silverlight代码。 编辑:将我的方法转移到答案

1 个答案:

答案 0 :(得分:0)

我将我的例子从我的问题转移到答案,因为没有其他人在22天内回答了这个问题。编辑:这更好。

   public partial class App : Application
   {               
            /// <summary>
            /// Initializes a new instance of the <see cref="App"/> class.
            /// </summary>
            public App()
            {
              this.Startup += (s, e) =>
              {
                // create and register it now
                SimpleIoc.Default.Register<IUserToken>(() => { return new UserToken(); });
                 SimpleIoc.Default.GetInstance<IUserToken>().PopulateUserTokenFromService(() =>
                {
                  // don't do anything until the user token is populated from the server
                  InitializeComponent();                 

                  this.RootVisual = new View();
                });
              }
            }