我已经启动了一个 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,所以我不确定我哪里出错了。