2010-12-22 109 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));