我正在尝试简单地使用 IOC 容器(目前为 ninject)作为 MVC5 的依赖项解析器。 这曾经在 MVC4、visual studio 2012 中运行良好,但现在使用 VS2013 和 MVC5,我无法让解析器在我的 Controller 中注入(inject)依赖项。这不是 ninject 特有的,我也尝试过 SimpleInjector 和 Unity -同样的错误
我只想在我的家庭 Controller 中注入(inject)这个类。
public interface ITest
{
void dummyMethod();
}
public class Test : ITest
{
public void dummyMethod()
{
};
}
这是依赖解析器
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver()
{
kernel = new StandardKernel();
AddBindings();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void AddBindings()
{
kernel.Bind<ITest>().To<Test>();
}
}
这是 global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
DependencyResolver.SetResolver(new NinjectDependencyResolver());
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
这是我的家庭 Controller
public class HomeController : Controller
{
public ActionResult Index(ITest test)
{
return View();
}
}
但是当我运行它时,我不断得到
Server Error in '/' Application.
Cannot create an instance of an interface.
我也试过创建一个全新的项目(MVC 5)——同样的错误
我试过MVC5,然后也升级到5.2.2。同样的错误
非常感谢任何帮助。我认为由于某种原因永远不会调用解析器,即使我在
kernel.Bind<ITest>().To<Test>();
它停在那里....不知道发生了什么:(
最佳答案
通常您不能将参数注入(inject)到您的操作方法中。
您需要在 Controller 的构造函数中注入(inject)依赖项:
public class HomeController : Controller
{
private readonly ITest test;
public HomeController(ITest test)
{
this.test = this;
}
public ActionResult Index()
{
//use test here
return View();
}
}
关于c# - 使用 IOC 容器作为 MVC5 的依赖解析器会引发 ' cannot create an instance of an interface ' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563755/