为什么structuremap没有选择home控制器
本文关键字:home 控制器 有选择 structuremap 为什么 | 更新日期: 2023-09-27 18:08:29
这是asp.net mvc3.
当我试着去我的主页/索引动作:
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!";
}
}
我得到错误:
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: }
我是否必须以某种方式手动连接每个控制器类?
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));
}
和我的结构化映射相关类:
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 IEnumerable<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;
}
}
您检查过是哪个对象给了您NullReferenceException
吗?
看起来你把container
赋值给了它自己:
private IContainer container;
public StructureMapControllerActivator(IContainer container)
{
container = container;
}
因此不设置成员变量。将构造函数中的行改为this.container = container
,然后就可以了。