2009-10-05 37 views
1

我看到大量關於如何使用ControllerBuilder.Current.SetControllerFactory注入服務的材料,但如果我想要解決模型中的服務又該怎麼辦?我需要從Controller層獲取它們並傳遞給它們嗎?ASP.NET MVC Unity - 在模型層注入

回答

1

理想情況下,您不應該注入服務到模型中,因爲這需要您向容器註冊模型。

如果您需要在模型實例中使用服務,請將該服務作爲方法參數傳遞,然後您可以將該服務注入控制器。

不知道更多關於它很難給出清晰的建議方案,但以下大綱可以幫助:

public interface IService 
{ 
    // ... describe the contract the service must fulfill 
} 

public class Model 
{ 
    public void DoSomething(IService service) 
    { 
    // ... do the necessary work using the service ... 
    } 
} 

public class AController : Controller 
{ 
    private readonly IService _injectedService; 

    public AController(IService injectedService) 
    { 
    _injectedService = injectedService; 
    } 
    public ActionResult SomeAction(int modelId) 
    { 
    // ... get the model from persistent store 
    model.DoSomething(_injectedService); 
    // ... return a view etc 
    } 
} 
+0

一個小點的是,許多(大多數?)的容器,這些天不要求在將具體類從容器中解析出來之前進行顯式容器註冊。所以如果依賴於IService,理論上可以解決「Model」類。 – 2011-11-08 14:39:10