2011-09-13 55 views
3

這是asp.net mvc3。爲什麼不是結構圖拿起我的HomeController?

當我嘗試去我家/ index動作:

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:  } 

我必須以某種方式手工線了每一個控制器類?

我的global.asax.cs有:

​​

而且我構成的地圖相關的類:

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; 

     } 
    } 
+1

哪個對象導致'NullReferenceException'? –

+0

好問題,看來容器是空的!我在我的global.asax.cs Application_Start方法中放置了一個斷點,並且它似乎以某種方式在調用StrucureMapControllerActivator時首先被調用?這怎麼可能? – Blankman

+1

啊,問題是:容器=容器應該是this.container =容器!畢竟,我想我應該給私人變量加個前綴_! – Blankman

回答

2

你檢查哪個對象給你NullReferenceException

它看起來就像你分配container將自己的位置:

private IContainer container; 
public StructureMapControllerActivator(IContainer container) 
{ 
    container = container; 
} 

所以成員變量從未設置。將構造函數中的行更改爲this.container = container,那麼您將很好。

相關問題