2010-12-22 103 views
1

以前我沒有爲我的通用存儲庫使用接口。當我提取從我的通用庫接口,我添加了兩個構造函數:一個無參數和參數的構造函數我收到以下錯誤:無法解析控制器

{"Resolution of the dependency failed, type = \"NascoBenefitBuilder.Controllers.ODSController\", name = \"(none)\". 
Exception occurred while: while resolving. 
Exception is: InvalidOperationException - The current type, ControllerLib.Models.Generic.IGenericRepository, is an interface and cannot be constructed. Are you missing a type mapping? 
----------------------------------------------- 
At the time of the exception, the container was: 
Resolving NascoBenefitBuilder.Controllers.ODSController,(none) 
Resolving parameter \"repo\" of constructor NascoBenefitBuilder.Controllers.ODSController(ControllerLib.Models.Generic.IGenericRepository repo) 
Resolving ControllerLib.Models.Generic.IGenericRepository,(none)"} 

我的控制器開頭:

public class ODSController : ControllerBase 
{ 
    IGenericRepository _generic = new GenericRepository(); 
} 

提取後該接口並在控制器中使用它:

public class ODSController : ControllerBase 
{ 
    IGenericRepository _generic; 
    public ODSController() : this(new GenericRepository()) 
    { 
    } 

    public ODSController(IGenericRepository repo) 
    { 
     _generic = repo; 
    } 
} 

當我使用參數化構造函數時,它拋出上面提到的錯誤。

任何人都可以幫助我解決這個問題嗎?

回答

2

您不再需要默認構造函數:

public class ODSController : ControllerBase 
{ 
    private readonly IGenericRepository _repository; 
    public ODSController(IGenericRepository repository) 
    { 
     _repository = repository; 
    } 
} 

然後確保你已經正確地配置了統一的容器:

IUnityContainer container = new UnityContainer() 
    .RegisterType<IGenericRepository, GenericRepository>(); 

而且你使用的是統一控制器廠Application_Start

ControllerBuilder.Current.SetControllerFactory(typeof(UnityControllerFactory)); 
相關問題