Sim*_*ons 1 c# asp.net asp.net-mvc dependency-injection unity-container
我有我的MVC5 Web控制器并尝试使用以下方法进行依赖注入:
public class PatientsController : Controller
{
public ISomeRepository _repo;
// GET: Patients
public ActionResult Index(ISomeRepository repo)
{
_repo = repo;
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
我的Unity配置如下所示:
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<ISomeRepository, SomeRepository>();
// GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = new UnityResolver(container);
}
Run Code Online (Sandbox Code Playgroud)
但是当我导航到控制器时,收到错误:
[MissingMethodException:无法创建接口的实例.]
您应该在控制器中使用构造函数注入,而不是在操作中注入实例.
public class PatientsController : Controller
{
private ISomeRepository _repo;
public PatientsController(ISomeRepository repo)
{
_repo = repo;
}
public ActionResult Index()
{
// use _repo here
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
561 次 |
| 最近记录: |