1

こんにちは、WebApi Mvc4 フレームワーク .net 4.0 を使用しています

次のように sessionFactory を作成します。

public void ConfigureNHibernate(IKernel container)
        {
            var sessionFactory = FluentNHibernate
                .Cfg.Fluently.Configure()
                .Database(
                    MsSqlConfiguration.MsSql2008.ConnectionString(
                        c => c.FromConnectionStringWithKey("ApikeysDb")))
                .CurrentSessionContext("web")
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<CTP.ApiNext.Data.SqlServer.SqlCommandFactory>())
                .BuildSessionFactory();

            // Add the ISessionFactory instance to the container
            container.Bind<ISessionFactory>().ToConstant(sessionFactory);

            // Configure a resolver method to be used for creating ISession objects
            container.Bind<ISession>().ToMethod(CreateSession);

            container.Bind<ICurrentSessionContextAdapter>().To<CurrentSessionContextAdapter>();
        }

以下で ISession オブジェクトを HTTP コンテキストにバインドすると、「オブジェクト参照が設定されていません」というエラーが表示されます

public ISession CreateSession(IContext context)
        {
            var sessionFactory = context.Kernel.Get<ISessionFactory>();
            if (!CurrentSessionContext.HasBind(sessionFactory))
            {
                // Open new ISession and bind it to the current session context
                var session = sessionFactory.OpenSession();
                CurrentSessionContext.Bind(session);
            }

            return sessionFactory.GetCurrentSession();
        }

エラーは次の行にあります: CurrentSessionContext.HasBind(sessionFactory)

エラーの詳細は次のとおりです。

[NullReferenceException: Object reference not set to an instance of an object.]
   lambda_method(Closure , Object ) +73
   NHibernate.Context.ReflectiveHttpContext.get_HttpContextCurrentItems() +84
   NHibernate.Context.WebSessionContext.GetMap() +52
   NHibernate.Context.MapBasedSessionContext.get_Session() +70
   NHibernate.Context.CurrentSessionContext.HasBind(ISessionFactory factory) +71
   CTP.ApiNext.Web.Api.App_Start.NinjectConfigurator.CreateSession(IContext context) in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectConfigurator.cs:91
   Ninject.Activation.Providers.CallbackProvider`1.CreateInstance(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\CallbackProvider.cs:45
   Ninject.Activation.Provider`1.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Provider.cs:38
   Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:157
   Ninject.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:386
   System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
   System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4077101
   Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:197
   Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:165
   Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:114
   Ninject.Activation.Providers.<>c__DisplayClass4.<Create>b__2(ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
   System.Linq.WhereSelectArrayIterator`2.MoveNext() +66
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +216
   System.Linq.Enumerable.ToArray(IEnumerable`1 source) +77
   Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
   Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:157
   Ninject.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:386
   System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
   System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4077101
   Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:197
   Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:165
   Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:114
   Ninject.Activation.Providers.<>c__DisplayClass4.<Create>b__2(ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
   System.Linq.WhereSelectArrayIterator`2.MoveNext() +66
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +216
   System.Linq.Enumerable.ToArray(IEnumerable`1 source) +77
   Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
   Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:157
   Ninject.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:386
   System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
   System.Linq.<CastIterator>d__b1`1.MoveNext() +85
   System.Linq.Enumerable.Single(IEnumerable`1 source) +191
   Ninject.ResolutionExtensions.Get(IResolutionRoot root, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:37
   CTP.ApiNext.Web.Api.App_Start.NinjectWebCommon.RegisterServices(IKernel kernel) in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectWebCommon.cs:61
   CTP.ApiNext.Web.Api.App_Start.NinjectWebCommon.CreateKernel() in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectWebCommon.cs:48
   Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs:50
   CTP.ApiNext.Web.Api.App_Start.NinjectWebCommon.Start() in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectWebCommon.cs:27

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +192
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +108
   System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +19
   WebActivator.BaseActivationMethodAttribute.InvokeMethod() +236
   WebActivator.ActivationManager.RunActivationMethods() +534
   WebActivator.ActivationManager.RunPreStartMethods() +41
   WebActivator.ActivationManager.Run() +64

[InvalidOperationException: The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +550
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +90
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +135
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9873912
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +456

私は非常に多くの投稿を読みましたが、役に立ちませんでした。

ISession を呼び出す MessageHandler (ninject によって呼び出される) があります。コメント アウトすると、問題は解決します。なんで?GlobalConfiguration.Configuration.MessageHandlers.Add(kernel.Get());

4

1 に答える 1

3

FactoryおよびSessionインターフェイスが正しくバインドされていません。Binding の一部としてスコープを設定するInSingletonScope必要があります (これらの 1 つだけが必要なため、Factory の場合、およびInThreadScopeSession の場合)。これは、Ninject が既存の参照をいつ挿入するか、各型の新しいインスタンスを作成するかを知るためです。

構成を次のように変更してみてください。

public void ConfigureNHibernate(IKernel container)
    {
        var sessionFactory = FluentNHibernate
            .Cfg.Fluently.Configure()
            .Database(
                MsSqlConfiguration.MsSql2008.ConnectionString(
                    c => c.FromConnectionStringWithKey("ApikeysDb")))
            .CurrentSessionContext("web")
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<CTP.ApiNext.Data.SqlServer.SqlCommandFactory>());

        // Bind the ISession Factory - Singleton as only ever need one of these
        container.Bind<ISessionFactory>().ToMethod(x =>configuration.BuildSessionFactory()).InSingletonScope();

        // Bind the ISession 
        container.Bind<ISession>().ToMethod(c => c.Kernel.Get<ISessionFactory>().OpenSession()).InThreadScope();

    }

上記をテストするには、すぐに Factory のインスタンス化を試みることができます。

var sessionFactory = Kernel.Get<ISessionFactory>();
于 2013-05-28T13:14:08.527 に答える