以前我没有为我的通用存储库使用接口。当我从通用存储库中提取接口时,我添加了两个构造函数:无参数和参数化构造函数我收到以下错误:
{"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;
}
}
当我使用参数化构造函数时,它会抛出上面提到的错误。
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:2)
您不再需要默认构造函数:
public class ODSController : ControllerBase
{
private readonly IGenericRepository _repository;
public ODSController(IGenericRepository repository)
{
_repository = repository;
}
}
然后确保您已正确配置Unity容器:
IUnityContainer container = new UnityContainer()
.RegisterType<IGenericRepository, GenericRepository>();
您正在使用Application_Start
中的Unity控制器工厂:
ControllerBuilder.Current.SetControllerFactory(typeof(UnityControllerFactory));