3

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

有没有一些常用的方法来使用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; 
} 

感谢您的帮助,请询问是否有不清晰..

+0

您是否在遵循PRISM指南? – mcabral

+0

刚开始使用Silverlight和MVVM时,我看到了Prism,但我打算在阶段2中进入它。 – Arthis

回答

2

在Silverlight中,你应该在组成根使用引导程序要连接您的整个对象图。这可能是应用程序类app.xml.cs和类似于

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

一般来说,这应该sufficant,但如果你需要为你的意见的独立工厂类,看看 Keeping the DI-container usage in the composition root in Silverlight and MVVM

+0

对不起,如果我花时间验证您的答案。但我需要它来探索这种方式(特别是链接...) – Arthis

1

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

+0

Ninject也。我的问题更多的是在Silverlight中集中所有对我的IOC容器的引用。如我的问题所详述,在MVC3中,您有DefaultControllerFactory。否则,我将使用静态类将呼叫打包到IOC容器... – Arthis