I have this setup:

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:

Type 'PositionReportApi.Controllers.PositionsController' does not have a default constructor

Stack trace:

at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)

I can't register an ISession.

How do i register an ISession that is created by a factory?

有帮助吗?

解决方案

From the stack trace I can see that you are using the new .NET 4.5 ASP.NET Web API and Simple Injector is not in the presented call graph. This probably means that you haven't configured the Simple Injector for use with the new Web API, which is a different registration than what you need for MVC (for some strange reason, and I sincerely hope they fix this in the final release). Since you didn't register a Simple Injector specific System.Web.Http.Dependencies.IDependencyResolver implementation to the Web API's GlobalConfiguration.Configuration.DependencyResolver, you'll get the default behavior, which will only work with default constructors.

Take a look at this Stackoverflow answer Does Simple Injector supports MVC 4 ASP.NET Web API? to see how to configure Simple Injector with the new ASP.NET Web API.

UPDATE

Note that you can get this exception even if you configured the DependencyResolver correctly, but when you didn't register register your Web API Controllers explicitly. This is caused by the way Web API is designed.

Always register your Controllers explicitly.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top