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