문제

I've seen a lot of different ways of configuring Ninject with ASP.NET MVC, but the implementation seems to change slightly with each release of the MVC framework. I'm trying to inject a RavenDB session into my repository. Here is what I have that's almost working.

public class MvcApplication : NinjectHttpApplication
{
    ...

    protected override void OnApplicationStarted()
    {
        base.OnApplicationStarted();

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

    protected override IKernel CreateKernel()
    {
        return new StandardKernel(new MyNinjectModule());
    }

    public static IDocumentSession CurrentSession
    {
        get { return (IDocumentSession)HttpContext.Current.Items[RavenSessionKey]; }
    }
    ...
}

public class MyNinjectModule : NinjectModule
{
    public override void Load()
    {
        Bind<IUserRepository>().To<UserRepository>();
        Bind<IDocumentSession>().ToConstant(MvcApplication.CurrentSession);
    }
}

When it tries to resolve IDocumentSession, I get the following error.

Error activating IDocumentSession using binding from IDocumentSession to constant value
Provider returned null.
Activation path:
  3) Injection of dependency IDocumentSession into parameter documentSession of constructor of type UserRepository

Any ideas on how to make the IDocumentSession resolve?

도움이 되었습니까?

해결책

ToConstant(MvcApplication.CurrentSession) is evaluated at application start. What you want is delayed evaluation ToMethod(ctx => MvcApplication.CurrentSession)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top