简体   繁体   中英

How to inject different dependencies into WebApi Controller using StructureMap

Currently I have an MVC application which also contains WebApi controllers.

I've set-up StructureMap to initialize using default conventions which handles service dependencies for both MVC and WebApi. This all works perfectly.

However, I have one Authentication service dependency which should be injected for WebApi and a different implementation for MVC. Since StructureMap has the same initialization bootstrap code, how do I switch depending on whether the request coming in is a WebApi endpoint or and Mvc controller endpoint?

Don't know if this is the best way of achieving this but I use the ObjectFactory.Configure method to override the initialization registries on boot-up but do this inside each SetResolver on Mvc's DependencyResolver.SetResolver and on WebApi's GlobalConfiguration.Configuration.ServiceResolver.SetResolver.

eg

 ObjectFactory.Configure(x => x.For<IAuthenticationService>() 
                        .Use(s => s.GetInstance<IMvcAuthenticationService>()));

and

 ObjectFactory.Configure(x => x.For<IAuthenticationService>() 
                        .Use(s => s.GetInstance<IWebApiAuthenticationService>()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM