我正在为 DI 使用 StructureMap,并且我的 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);
}
}
结构图代码:
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 参数为空。如果我从构造函数中删除 this(null),我仍然会得到 null。
也许我的 BaseController 的无参数构造函数没有正确编写?如果我手动解析 IAuctionCmsServices,它会起作用。这意味着 IAuctionCmsServices 已正确注册但未被注入。