我创建了一个初学者MVC 3应用程序安装程序,并在构造函数中传递了一个控制器构造函数--一个ModelStateDictionary对象。这是来自System.Web.Mvc命名空间的对象。
错误激活ModelStateDictionary使用ModelStateDictionary的隐式自绑定检测出两个服务的构造函数之间的周期性依赖。
激活路径: 3)将依赖ModelStateDictionary注入到ModelStateDictionary类型构造函数的参数字典中;2)向HomeController 1型构造函数的参数modelDict中注入依赖ModelStateDictionary
我如何解决这个问题?我怎么把它抽象成工作的方式呢?有可能吗?我搜索了Stackoverflow和ninject.org ..。但是在这里不知道它是如何应用的,因为我不能直接修改ModelStateDictionary。
public class HomeController : Controller
{
private readonly ModelStateDictionary _modelDict;
public HomeController(ModelStateDictionary modelDict)
{
_modelDict = modelDict;
}
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
}
public void SetupDependencyInjection()
{
IKernel kernel = new StandardKernel();
//kernel.Bind<>().To<>();
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
public class NinjectDependencyResolver : IDependencyResolver
{
private readonly IResolutionRoot _resolutionRoot;
public NinjectDependencyResolver(IResolutionRoot kernel)
{
_resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
return _resolutionRoot.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _resolutionRoot.GetAll(serviceType);
}
}这是一个简单的例子,我不会在我自己的代码中使用这种方式.但情况和理论是一样的。ModelStateDictionary应该是隐式自绑定的。尽管存在不接受参数的构造函数,但Ninject选择了接受ModelStateDictionary对象的构造函数。如果参数最多的构造函数不能正常工作,那么九点对象不应该返回到没有参数的构造函数中吗?
发布于 2012-02-27 11:18:41
不,尼尼莫不会尝试构造函数,直到它找到一个不会失败的构造函数。它选择参数最多的构造函数,并使用它的绑定。如果构造函数失败,则引发异常。
https://stackoverflow.com/questions/9459965
复制相似问题