2012-09-17 113 views
1

我已經啓動了一個Web API項目,並將其擴展爲一個正常的MVC項目。我的意思是我有一些控制器來自ApiController和其他來自ControllerWeb API和MVC 4控制器中使用StructureMap的問題

這裏是我的DependencyResolver:

public class StructureMapDependencyResolver :IDependencyResolver 
{ 
    public IDependencyScope BeginScope() 
    { 
     return this; 
    } 

    public StructureMapDependencyResolver(IContainer container) 
    { 
     _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 serviceType) 
    { 
     return _container.GetAllInstances<object>() 
         .Where(s => s.GetType() == serviceType); 
    } 

    private readonly IContainer _container; 

    public void Dispose() { } 
} 

,這裏是我的Global.asax.cs:

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 

    RouteConfig.RegisterRoutes(RouteTable.Routes); 
    BundleConfig.RegisterBundles(BundleTable.Bundles); 

    ObjectFactory.Initialize(x => 
     { 
      x.For<IDataService>().Use<MockDataService>(); 
     }); 
    ObjectFactory.Configure(x => x.Scan(scan => 
     { 
      scan.AssembliesFromApplicationBaseDirectory(); 
      scan.LookForRegistries(); 
      scan.TheCallingAssembly(); 
      scan.WithDefaultConventions(); 
     })); 

    var container = ObjectFactory.Container; 
    GlobalConfiguration.Configuration.DependencyResolver = 
       new StructureMapDependencyResolver(container); 
} 

在Web API控制器工作的偉大,但我不能讓構造器注入到工作中Controller來自派生的。當然這是通常的No parameterless constructor defined for this object錯誤信息。

我在這裏有點損失......這是我第一次進入Web API,因此我不確定我要出錯的地方。

回答

2

您需要調用DependencyResolver.SetResolver到您的MVC IOC容器。確保你的容器也實現了MVC的IDependencyResolver,否則它將不適用於MVC。