Asp.net 无法解析控制器
以前,我没有为我的通用存储库使用接口。当我从我的通用存储库中提取接口时,我添加了两个构造函数:一个无参数构造函数和一个参数化构造函数。我得到以下错误:Asp.net 无法解析控制器,asp.net,asp.net-mvc-2,dependency-injection,Asp.net,Asp.net Mvc 2,Dependency Injection,以前,我没有为我的通用存储库使用接口。当我从我的通用存储库中提取接口时,我添加了两个构造函数:一个无参数构造函数和一个参数化构造函数。我得到以下错误: {"Resolution of the dependency failed, type = \"NascoBenefitBuilder.Controllers.ODSController\", name = \"(none)\". Exception occurred while: while resolving. Exception is: I
{"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;
}
}
当我使用参数化构造函数时,它抛出了上面提到的错误
有人能帮我解决这个问题吗?您不再需要默认构造函数:
public class ODSController : ControllerBase
{
private readonly IGenericRepository _repository;
public ODSController(IGenericRepository repository)
{
_repository = repository;
}
}
然后确保已正确配置Unity容器:
IUnityContainer container = new UnityContainer()
.RegisterType<IGenericRepository, GenericRepository>();
ControllerBuilder.Current.SetControllerFactory(typeof(UnityControllerFactory));