SimpleInjector: Injection does not work with MVC 4 ASP.NET Web API

I have this setting:

public static void Initialize(ISessionFactory factory) { var container = new Container(); InitializeContainer(container, factory); container.RegisterMvcControllers( Assembly.GetExecutingAssembly()); container.RegisterMvcAttributeFilterProvider(); container.Verify(); DependencyResolver.SetResolver( new SimpleInjectorDependencyResolver(container)); } private static void InitializeContainer( Container container, ISessionFactory factory) { container.RegisterPerWebRequest<ISession>( () => factory.OpenSession(), true); } 

The Initialize method is called in Application_Start :

 public class WebApiApplication : HttpApplication { protected void Application_Start() { SimpleInjectorInitializer.Initialize( new NHibernateHelper( Assembly.GetCallingAssembly(), this.Server.MapPath("/")) .SessionFactory); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } 

But when I try to call the controller action, I get an ArgumentException :

The type 'PositionReportApi.Controllers.PositionsController' does not have a default constructor

Stack trace:

in System.Linq.Expressions.Expression.New (type type) in System.Web.Http.Internal.TypeActivator.Create [TBase] (instanceType type) in System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create (HttpRequestMessrolD request Hesspler, Request controllerDescriptor, type controllerType)

I can not register ISession .

How to register an ISession created using factory?

+3
dependency-injection session nhibernate simple-injector registration
Jul 05 '12 at 15:05
source share
1 answer

From the stack trace, I can see that you are using the new .NET 4.5 ASP.NET Web API and Simple Injector not in the call schedule presented. This probably means that you did not configure Simple Injector to use with the new web API, which is different from what you need for MVC (for some strange reason, and I sincerely hope that they fix this in the final version) . Since you have not registered a specific implementation of System.Web.Http.Dependencies.IDependencyResolver Simple Injector for the GlobalConfiguration.Configuration.DependencyResolver web API, you will get a default behavior that will only work with default constructors.

Take a look at this answer. Stackoverflow Simple Injector supports MVC 4 ASP.NET Web API? to learn how to configure Simple Injector using the new ASP.NET API webpage.

UPDATE

Note that you can get this exception even if you configured DependencyResolver correctly, but when you did not register the registration of your web API controllers explicitly. This is due to the way the Web API is developed.

Always register your controllers explicitly.

+6
Jul 05 2018-12-17T00:
source share



All Articles