我正在尝试使用Web API 2设置结构图ver 3.0.5.0.
我已经遵循了这个实现:Configuring dependency injection with ASP.NET Web API 2.1
但是,在针对ComplexesController进行攻击时出现此错误:
尝试创建“ComplexesController”类型的控制器时发生错误.确保控制器具有无参数的公共构造函数.
谁能看到我的structuremap配置有什么问题?永远不会调用Create方法.
这是我的实施:
public class StructureMapControllerActivator : IHttpControllerActivator { private readonly IContainer _container; public StructureMapControllerActivator(IContainer container) { if (container == null) throw new ArgumentNullException("container"); _container = container; } public IHttpController Create(HttpRequestMessage request,HttpControllerDescriptor controllerDescriptor,Type controllerType) { try { var scopedContainer = _container.GetNestedContainer(); scopedContainer.Inject(typeof(HttpRequestMessage),request); request.RegisterForDispose(scopedContainer); return (IHttpController)scopedContainer.GetInstance(controllerType); } catch (Exception e) { // TODO : Logging throw e; } } }
这个方法在我的创业公司……
public void InitializeContainer() { // STRUCTURE MAP Container container = new Container(); GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator),new StructureMapControllerActivator(container)); container.Configure(x => x.For<IForumRepository>().Use<ForumRepository>()); container.Configure(x => x.For<IComplexRepository>().Use<ComplexRepository>()); }
..这是控制器:
public class ComplexesController : ApiController { private IComplexRepository _repo; public ComplexesController(IComplexRepository repo) { _repo = repo; } // GET: api/Complexes public IList<Complex> GetComplexes() { var complexes = _repo.GetList(); return complexes; } ...
我的完整启动课程
[assembly: OwinStartup(typeof(AngularJSAuthentication.API.Startup))] namespace AngularJSAuthentication.API { public class Startup { public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); } } }
解决方法
这里的问题是您使用GlobalConfiguration对象而不是HttpConfiguration对象注册服务激活器.在这种情况下,GlobalConfiguration对象永远不会被使用,因为它被HttpConfiguration对象替换.为了解决您的问题,您应该使用以下内容替换InitializeContainer()方法.
public void InitializeContainer(HttpConfiguration config) { // STRUCTURE MAP Container container = new Container(); config.Services.Replace(typeof(IHttpControllerActivator),new StructureMapControllerActivator(container)); container.Configure(x => x.For<IForumRepository>().Use<ForumRepository>()); container.Configure(x => x.For<IComplexRepository>().Use<ComplexRepository>()); }
然后,您应该将HttpConfiguration对象从Startup类传递给新的InitializeContainer()方法.
希望这可以帮助.
-B