我使用StructureMap为DI时遇到有不正确实例我MVC3自定义的基本控制器的问题。而不是传递一个IAuctionCmsServices的实例,我得到空。MVC控制器注射自定义的基本控制器不工作
我的控制器:
public class BaseController : Controller
{
public IAuctionCmsServices AuctionCmsServices;
public BaseController()
: this(null) <--- is this the problem?
{
}
public BaseController(IAuctionCmsServices auctionCmsServices)
{
this.AuctionCmsServices = auctionCmsServices;
}
}
public class HomeController : BaseController
{
public ActionResult Index()
{
return View);
}
}
StructureMap代码:
public class StructureMapContainer : IDependencyResolver
{
static IContainer _container;
public StructureMapContainer(IContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
if (serviceType.IsAbstract || serviceType.IsInterface)
{
return _container.TryGetInstance(serviceType);
}
else
{
System.Diagnostics.Debug.WriteLine(_container.WhatDoIHave());
return _container.GetInstance(serviceType);
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances<object>().Where(s => s.GetType() == serviceType);
}
}
public class ApplicationRegistry : Registry
{
public ApplicationRegistry()
{
For<IAuctionCmsServices>().HybridHttpOrThreadLocalScoped().Use<AuctionCmsServices>();
}
}
在的global.asax.cs:
DependencyResolver.SetResolver(new StructureMapContainer(container));
当调用BaseController的构造函数中,IAuctionCmsServices参数为null。如果我从构造函数中删除这个(null),我仍然会得到null。
也许我BaseController的paramterless构造函数没有正确写的?如果我手动为IAuctionCmsServices解决问题,则可以使用。这意味着IAuctionCmsServices已正确注册但未被注入。
我知道这可能不是一个有用的评论,但为什么不是NinJect? – Joe 2012-04-10 18:55:56
你是对的,没有帮助。我不认为容器是这里的问题。 – rboarman 2012-04-10 19:14:26