Why isn't structuremap picking up my HomeController?
This is asp.net mvc3.
When I try and go to my home/index action:
public class HomeController : Controller
{
private IBar bar;
public HomeController(IBar bar)
{
this.bar = bar;
}
//
// GET: /Home/
public ActionResult Index()
{
ViewBag.Message = "hello world yo: " + bar.SayHi();
return View();
}
}
public interface IBar
{
string SayHi();
}
public class Bar : IBar
{
public string SayHi()
{
return "Hello from BarImpl!";
}
}
I get the error:
System.NullReferenceException: Object reference not set to an instance of an object.
public IController Create(RequestContext requestContext, Type controllerType)
Line 98: {
Line 99: return container.GetInstance(controllerType) as IController;
Line 100:
Line 101: }
Do I have to somehow manually wire up each and every controller class?
My global.asax.cs has:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
IContainer container = new Container(
x =>
{
x.Scan(s =>
{
s.AssembliesFromApplicationBaseDirectory();
s.WithDefaultConventions();
s.LookForRegistries();
}
);
x.For<IControllerActivator>().Use<StructureMapControllerActivator>();
x.For<IBar>().Use<Bar>();
}
);
DependencyResolver.SetResolver(new StructuredMapDependencyResolver(container));
}
And my structured map related classes:
public class StructuredMapDependencyResolver : IDependencyResolver
{
private IContainer container;
public StructuredMapDependencyResolver(IContainer container)
{
this.container = container;
}
public object GetService(Type serviceType)
{
if (serviceType.IsAbstract || serviceType.IsInterface)
{
return container.TryGetInstance(serviceType);
}
return container.GetInstance(serviceType);
}
public I开发者_JAVA百科Enumerable<object> GetServices(Type servicesType)
{
//return container.GetAllInstances(servicesType) as IEnumerable<object>;
return container.GetAllInstances<object>()
.Where(s => s.GetType() == servicesType);
}
}
public class StructureMapControllerActivator : IControllerActivator
{
private IContainer container;
public StructureMapControllerActivator(IContainer container)
{
container = container;
}
public IController Create(RequestContext requestContext, Type controllerType)
{
return container.GetInstance(controllerType) as IController;
}
}
Have you checked which object is giving you the NullReferenceException
?
It looks like you're assigning container
to itself here:
private IContainer container;
public StructureMapControllerActivator(IContainer container)
{
container = container;
}
So the member variable is never set. Change the line in the constructor to this.container = container
and you'll be good to go.
精彩评论