我正在使用StructureMap进行DI,并且我的MVC3自定义基本控制器没有被正确实例化。我没有传递IAuctionCmsServices的实例,而是获得了null。
我的控制器:
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。如果我从构造函数中删除this(null),我仍然会得到null。
也许我的BaseController的无参数构造函数写得不正确?如果我手动解析IAuctionCmsServices,它可以工作。这意味着IAuctionCmsServices已正确注册但未注入。
答案 0 :(得分:0)
你是从样本中省略了构造函数HomeController还是没有?
我不是很熟悉StructureMap,所以除非它对IL做了一些魔法,如果它没有接受它的构造函数,该属性应该如何注入HomeController?
IE
public HomeController(IAuctionCmsServices auctionCmsServices)
: base(auctionCmsServices)
{}
道歉,如果我是密集或遗失的东西。