【问题标题】:IOC and Silverlight国际奥委会和 Silverlight
【发布时间】:2011-09-02 08:40:47
【问题描述】:

在 mvc asp.net 中,我可以重写一个工厂来创建我的控制器,所以在这里放一个对我的 IOC 的引用。我的控制器的构造函数需要的每个接口都将由我的 IOC 提供。

是否有一些使用 Silverlight 的常用方法? 目前我只发现到处都在使用 Ninject 的内核:

public partial class MyUserControlSL   
{
    public MyUserControlSL()
    {
        DataContext = new MyViewModel(Kernel.Get<IMyRepository>());
        InitializeComponent();
    }
}

例如使用 StructureMap 和 MVC:

public class ControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(
        RequestContext requestContext, Type controllerType)
    {
        IController result = null;
        try
        {
            if (controllerType != null)
            {
                result = ObjectFactory.GetInstance(controllerType) 
                    as Controller;
            }
            else
            {
                return base.GetControllerInstance(
                    requestContext, controllerType);
            }
        }
        catch (StructureMapException)
        {
            System.Diagnostics.Debug.WriteLine(
                ObjectFactory.WhatDoIHave());
            throw;
        }

        return result;
    }
}

public AController(IServiceA serviceA)
{
    if (serviceA == null)
    {
        throw new Exception("IServiceA cannot be null");
    }
    _ServiceA = serviceA;
}

public ServiceA(IRepositoryA repository)
{
    if (repository == null)
    {
        throw new Exception(
            "the repository IRepositoryA cannot be null");
    }

    _Repository = repository;
}

感谢您的帮助,如果不清楚请询问..

【问题讨论】:

  • 您是否按照 PRISM 指南工作?
  • 刚开始使用 silverlight amd MVVM,我看到了 Prism,但我打算在第 2 阶段进入它。

标签: c# .net silverlight dependency-injection inversion-of-control


【解决方案1】:

在 Silverlight 中,您应该在组合根目录中使用引导程序来连接您的整个对象图。它可能是应用程序类 app.xml.cs,看起来类似于

public partial class App : Application
{
   private void Application_Startup(object sender, StartupEventArgs e)
   {
       Bootstrapper bootstrapper = new Bootstrapper();
       bootstrapper.Run();
   }
}

一般来说,这应该足够了,但是如果您需要一个单独的工厂类来保存您的视图,请查看 Keeping the DI-container usage in the composition root in Silverlight and MVVM.

【讨论】:

  • 对不起,如果我需要时间来验证您的答案。但我需要它来探索这种方式(尤其是链接...)
【解决方案2】:

对于 Silverlight,您可以使用带有自定义 IoC 容器的 PRISM 框架。

【讨论】:

  • 忍者也。我的问题更多的是在silverlight中集中对我的IOC容器的所有引用。如我的问题中所述,在 MVC3 中,您拥有 DefaultControllerFactory。否则我将使用静态类来包装对 IOC 容器的调用...
【解决方案3】:

【讨论】:

  • 忍者也。我的问题更多的是在silverlight中集中对我的IOC容器的所有引用。如我的问题中所述,在 MVC3 中,您拥有 DefaultControllerFactory。否则我将使用静态类来包装对 IOC 容器的调用...
猜你喜欢
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
  • 1970-01-01
相关资源
最近更新 更多