使用StructureMap的Web API和MVC 4控制器中的问题

时间:2012-09-17 02:31:22

标签: asp.net-mvc-4 asp.net-web-api structuremap

我已经启动了一个Web API项目,并将其扩展为一个普通的MVC项目。我的意思是我有一些来自ApiController的控制器和来自Controller的其他控制器。

这是我的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所以我不确定我哪里出错了。

1 个答案:

答案 0 :(得分:2)

您需要将DependencyResolver.SetResolver调用到您的MVC IOC容器中。确保你的容器也实现了MVC的IDependencyResolver,否则它将不适用于MVC。