Ich verwende StructureMap für DI und habe ein Problem mit meinem MVC3 Custom Base Controller nicht korrekt instanziiert. Anstatt eine Instanz von IAuctionCmsServices zu übergeben, bekomme ich null.MVC-Controller-Injektion mit benutzerdefinierten Basis-Controller funktioniert nicht
Meine Controller:
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 Code:
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>();
}
}
In global.asax.cs:
DependencyResolver.SetResolver(new StructureMapContainer(container));
Wenn Konstruktor des Base aufgerufen wird, die IAuctionCmsServices Parameter null ist. Wenn ich das this (null) aus dem Konstruktor entferne, bekomme ich immernoch null.
Vielleicht ist mein parameterloser Konstruktor von BaseController nicht korrekt geschrieben? Wenn ich IAuctionCmsServices manuell auflösung, funktioniert es. Dies bedeutet, dass IAuctionCmsServices korrekt registriert ist, aber nicht injiziert wird.
Ich weiß, dass dies kein hilfreicher Kommentar sein könnte, aber warum nicht NinJect? – Joe
Sie haben Recht, nicht hilfreich. Ich glaube nicht, dass hier der Container das Thema ist. – rboarman