我已经启动了一个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所以我不确定我哪里出错了。
答案 0 :(得分:2)
您需要将DependencyResolver.SetResolver调用到您的MVC IOC容器中。确保你的容器也实现了MVC的IDependencyResolver,否则它将不适用于MVC。