我使用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