No parametless constructor defined Hangfire Ninject - asp.net-mvc-5

I'm having a problem activating instance of my class with no parametless constructor defined.
The constructor:
public HangfireExecutor(ICommandDispatcher commandDispatcher, IQueryDispatcher queryDispatcher, IMapper mapper)
How I register and configure Hangfire (three dots are used instead of sensitive info):
[assembly: OwinStartupAttribute(typeof(Web2.Startup))]
public partial class Startup
private IAppBuilder _app;
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
_app = app;
GlobalConfiguration.Configuration.UseSqlServerStorage("...");
_app.UseHangfireDashboard("/...", new DashboardOptions
{
Authorization = new[] { new HangfireDashboardAuthorizationFilter() },
AppPath = "/Identity/Create"
});
_app.UseHangfireServer();
_app.UseNinjectMiddleware(CreateKernel);
}
Registration in IoC container:
public partial class Startup
{
...
protected IKernel CreateKernel()
{
var kernel = new StandardKernel();
...
kernel.Bind<HangfireExecutor>().ToSelf().InBackgroundJobScope();
GlobalConfiguration.Configuration.UseNinjectActivator(kernel);
return kernel;
The error:
System.MissingMethodException
No parameterless constructor defined for this object hangfire ninject System.RuntimeTypeHandle.CreateInstance
System.MissingMethodException: No parameterless constructor defined for this object
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Hangfire.JobActivator.ActivateJob(Type jobType)
at Hangfire.JobActivator.SimpleJobActivatorScope.Resolve(Type type)
at Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext context)
For me it looks like the Hangfire does not use Ninject activator (?) but I don't know why.
I've followed both tutorials: on Hangfire site and Hangfire.Ninject github and several github repos and SO questions.
Instatiating other classes not used by Hangfire works well; also instatiating Hangfire executor with parametless constructor works properly.
I'm using:
ASP .NET MVC 5
.NET Framework 4.6.1,
Hangfire 1.6.21
Hangfire.Ninject 1.2

As method _app.UseNinjectMiddleware(CreateKernel); does not create kernel (just keeps delegate to the metod creating the kernel) the correct order of commands in Hangfire configuration in my case should be:
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
_app = app;
GlobalConfiguration.Configuration.UseSqlServerStorage("...");
_app.UseHangfireDashboard("/...", new DashboardOptions
{
Authorization = new[] { new HangfireDashboardAuthorizationFilter() },
AppPath = "/Identity/Create"
});
_app.UseNinjectMiddleware(CreateKernel);
}
and then at the end of CreateKernel method:
kernel.Bind<HangfireExecutor>().ToSelf().InBackgroundJobScope();
GlobalConfiguration.Configuration.UseNinjectActivator(kernel);
_app.UseHangfireServer();
return kernel;
Now Hangfire started resolving dependencies. I think that it is important to create kernel as soon after starting the app as possible - otherwise Hangfire may not be initialized and background jobs will not be executed.

Related

Blazor Server Authentication not working after publishing to Azure

I am creating a Blazor Server app and Implemented Authentication using Identity Server.
Everything was working fine until I published it to Azure. Everything is working except Login & Register which return
"Sorry, there's nothing at this address."
When I click Login Azure log stream shows this exception
An unhandled exception has occurred while executing the request.
System.InvalidProgramException: Common Language Runtime detected an invalid program.
at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope )
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelActivatorProvider.<>c__DisplayClass1_0.<CreateActivator>b__0(PageContext context)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelFactoryProvider.<>c__DisplayClass3_0.<CreateModelFactory>b__0(PageContext pageContext)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.CreateInstance()
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
and Register:
An unhandled exception has occurred while executing the request.
System.Security.SecurityException: Invalid assembly public key. (0x8013141E)
at System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
at System.Reflection.RuntimePropertyInfo.get_Signature()
at System.Reflection.RuntimePropertyInfo.get_PropertyType()
at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultPageApplicationModelProvider.CreateModel(PageActionDescriptor actionDescriptor, TypeInfo pageTypeInfo)
at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultPageApplicationModelProvider.OnProvidersExecuting(PageApplicationModelProviderContext context)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageLoader.LoadAsyncCore(PageActionDescriptor actionDescriptor)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageLoaderMatcherPolicy.ApplyAsyncAwaited(CandidateSet candidates, Task`1 actionDescriptorTask, Int32 index)
at Microsoft.AspNetCore.Routing.Matching.DfaMatcher.SelectEndpointWithPoliciesAsync(HttpContext httpContext, IEndpointSelectorPolicy[] policies, CandidateSet candidateSet)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatch|8_1(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task matchTask)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
and my startup page is:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IDisplayMessage, DisplayMessage>();
services.AddServices();
services.AddScoped<IAuthenticationStateService, AuthenticationStateServiceServerSide>();
services.AddAuthentication();
services.AddDbContextPool<MainDbContext>(options => options
.UseLoggerFactory(MyLoggerFactory)
.EnableSensitiveDataLogging()
.UseMySql(Configuration.GetConnectionString(db), mySqlOptions => mySqlOptions
.ServerVersion(new Version(8, 0, 19), ServerType.MySql)));
services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
})
.AddSignInManager<ApplicationSignInManager>()
.AddEntityFrameworkStores<MainDbContext>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();
var assemlies = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Where(a => a.FullName.StartsWith("LaWeb")).Select((item) => Assembly.Load(item)).ToList();
assemlies.Add(Assembly.GetExecutingAssembly());
services.AddAutoMapper(assemlies);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
It works perfectly when runnning from visual studio or when publishing localy to a folder and then running using cmd...

AfterMap with IMappingAction and IHttpContextAccessor throwing error

I have followed the example found here. I have a class as follows:
```
public class FileServiceRequestMappingAction : IMappingAction
{
private readonly IHttpContextAccessor _httpContextAccessor;
public FileServiceRequestMappingAction(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void Process(FileServiceRequest source, FileSearchRequest destination)
{
try
{
destination.Filter = "somevalue";
var storageType = "somestoragetype";
if (_httpContextAccessor.HttpContext.Request.Path.Value.ToLower().Contains("/patha/"))
{
storageType = "someothertypeofstorage";
}
if (!string.IsNullOrWhiteSpace(destination.Filter))
{
destination.Filter += $" and storageType eq {storageType}";
}
else
{
destination.Filter += $"storageType eq {storageType}";
}
}
catch (Exception ex)
{
throw new TranslationException($"Error in filter. {ex.Message}");
}
}
}
```
In my startup I have:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAutoMapper(typeof(FileServiceRequestMappingAction).Assembly);
When I fire up the app and execute my api query where the map is called, I get the following error:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at AutoMapper.Configuration.MappingExpression`2.<>c__60`1.<AfterMap>g__AfterFunction|60_0(TSource src, TDestination dest, ResolutionContext ctxt) in C:\projects\automapper\src\AutoMapper\Configuration\MappingExpression.cs:line 450
at lambda_method(Closure , FileServiceRequest , FileSearchRequest , ResolutionContext )
at lambda_method(Closure , Object , Object , ResolutionContext )
at AutoMapper.Mapper.AutoMapper.IMapper.Map[TDestination](Object source) in C:\projects\automapper\src\AutoMapper\Mapper.cs:line 207
The error message is:
No parameterless constructor defined for this object.
I am sure I'm doing something wrong. Note that in the startup.cs file, I have tried services.AddAutoMapper(typeof(Startup).Assembly); as well. It doesn't work either.
Any thoughts, anyone?
Thanks.
just FYI: I fixed this by switching to using a Profile instead of a direct map.

Connecting to WCF service from Azure Functions and trouble-shooting assembly bindings

Where can I see the Assembly that Azure functions is trying to load ? (Like fuslogvw on windows)
Update
Update the title as requested to better reflect the accepted answer
Update
Changed my code to 'manually' construct the SOAP request using WebClient and it works ... so me thinks somewhere the WCF service proxy is not playing well within the sandbox that is Azure Functions ... Nevertheless I would still like an answer as to how we can see the Assembly binding log views.
Original Post
I keep getting the same error :
2016-11-17T10:32:44.392 System.IO.FileNotFoundException: The filename,
directory name, or volume label syntax is incorrect. (Exception from
HRESULT: 0x8007007B)
Server stack trace:
at
System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32
errorCode, IntPtr errorInfo)
at Microsoft.Win32.Fusion.ReadCache(ArrayList alAssems, String
name, UInt32 nFlag)
at System.Reflection.RuntimeAssembly.EnumerateCache(AssemblyName
partialName)
at
System.Reflection.RuntimeAssembly.LoadWithPartialNameInternal(AssemblyName
an, Evidence securityEvidence, StackCrawlMark& stackMark)
at System.Reflection.Assembly.LoadWithPartialName(String
partialName, Evidence securityEvidence)
at System.Xml.Serialization.TempAssembly.LoadGeneratedAssembly(Type
type, String defaultNamespace, XmlSerializerImplementation& contract)
at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[]
mappings, Type type)
at
System.ServiceModel.Description.XmlSerializerOperationBehavior.Reflector.SerializerGenerationContext.GenerateSerializers()
at
System.ServiceModel.Description.XmlSerializerOperationBehavior.Reflector.SerializerGenerationContext.GetSerializer(Int32
handle)
at
System.ServiceModel.Description.XmlSerializerOperationBehavior.Reflector.MessageInfo.get_BodySerializer()
at
System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter
writer, MessageVersion version, String action, MessageDescription
messageDescription, Object returnValue, Object[] parameters, Boolean
isRequest)
at
System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter
writer, MessageVersion version, Object[] parameters, Object
returnValue, Boolean isRequest)
at
System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter
writer)
at
System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter
writer)
at
System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter
writer)
at
System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message
message, Stream stream)
at
System.ServiceModel.Channels.HttpOutput.WriteStreamedMessage(TimeSpan
timeout)
at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
at
System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.SendRequest(Message
message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message
message, TimeSpan timeout)
at
System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action,
Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
Object[] outs, TimeSpan timeout)
at
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
message)
Exception rethrown at [0]:
at
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg)
at
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type)
Currently, there is no support to view assembly binding logs. Enabling diagnostic logs will help debug most of the errors. Also take a look at logging tips and tricks.
Here is a sample for connecting to a WCF service hosted in Azure from your function:
Got to Function App Settings --> Go to Kudu --> Go to D:\home\site\wwwroot\YourFunction
Create folder bin
Upload System.ServiceModel.dll
Upload WCF service contract IService1.csx. You can do this from either Kudu or View Files on the portal
#r "System.ServiceModel.dll"
using System.ServiceModel;
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
string WelComeMessage(String name);
}
Sample queue trigger that invokes WCF endpoint:
#r "System.ServiceModel.dll"
#load "IService1.csx"
using System;
using System.ServiceModel;
public static void Run(string myQueueItem, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {myQueueItem}");
BasicHttpBinding b = new BasicHttpBinding();
EndpointAddress ea = new EndpointAddress("http://YourServiceAddress/service1.svc?wsdl");
var myChannelFactory = new ChannelFactory<IService1>(b, ea);
IService1 client = myChannelFactory.CreateChannel();
var msg= client.WelComeMessage("HelloWorld");
((ICommunicationObject)client).Close();
log.Info($"Hello from WCF: {msg}");
}
Hope this helps!

Xamarin SKPaymentQueue AddPayment throwing exception

In my Xamarin app when I call this method
private void MakePayment (SKProduct product)
{
SKPayment payment = SKPayment.PaymentWithProduct (product);
SKPaymentQueue.DefaultQueue.AddPayment (payment);
}
I get this error:
Failed to marshal the Objective-C object 0x14607110 (type:
SKPaymentTransaction). Could not find an existing managed instance for
this object, nor was it possible to create a new managed instance
(because the type 'MonoTouch.StoreKit.SKPaymentTransaction[]' does not
have a constructor that takes one IntPtr argument).
I'm not sure if I have something configured wrong or there is an issue in my code or Xamarin.
Here's the code for the Observer
internal class CustomPaymentObserver : SKPaymentTransactionObserver
{
private InAppPurchase inAppPurchase;
public CustomPaymentObserver (InAppPurchase inAppPurchase)
{
this.inAppPurchase = inAppPurchase;
}
public override void UpdatedTransactions (SKPaymentQueue queue, SKPaymentTransaction[] transactions)
{
Console.WriteLine ("UpdatedTransactions");
foreach (SKPaymentTransaction transaction in transactions) {
switch (transaction.TransactionState) {
case SKPaymentTransactionState.Purchased:
inAppPurchase.CompleteTransaction (transaction);
break;
case SKPaymentTransactionState.Failed:
inAppPurchase.FailedTransaction (transaction);
break;
default:
break;
}
}
}
public override void PaymentQueueRestoreCompletedTransactionsFinished (SKPaymentQueue queue)
{
}
public override void RestoreCompletedTransactionsFailedWithError (SKPaymentQueue queue, NSError error)
{
}
}
Here is the full stack trace:
System.Exception: Failed to marshal the Objective-C object 0x17ecb680 (type: SKPaymentTransaction). Could not find an existing managed instance for this object, nor was it possible to create a new managed instance (because the type 'MonoTouch.StoreKit.SKPaymentTransaction[]' does not have a constructor that takes one IntPtr argument).
at MonoTouch.ObjCRuntime.Runtime.MissingCtor (IntPtr ptr, IntPtr klass, System.Type type, MissingCtorResolution resolution) [0x00046] in /Developer/MonoTouch/Source/monotouch/src/ObjCRuntime/.pp-Runtime.cs:352
at MonoTouch.ObjCRuntime.Runtime.ConstructNSObject[NSObject] (IntPtr ptr, System.Type type, MissingCtorResolution missingCtorResolution) [0x00000] in :0
at MonoTouch.ObjCRuntime.Runtime.GetNSObject (IntPtr ptr, System.Type target_type, MissingCtorResolution missingCtorResolution, System.Boolean& created) [0x00073] in /Developer/MonoTouch/Source/monotouch/src/ObjCRuntime/.pp-Runtime.cs:514
at MonoTouch.ObjCRuntime.Runtime.GetNSObjectWrapped (IntPtr ptr, IntPtr type_ptr, System.Boolean& created) [0x0000c] in /Developer/MonoTouch/Source/monotouch/src/ObjCRuntime/.pp-Runtime.cs:686
at at (wrapper native-to-managed) MonoTouch.ObjCRuntime.Runtime:GetNSObjectWrapped (intptr,intptr,int&)
at at (wrapper managed-to-native) MonoTouch.ObjCRuntime.Messaging:void_objc_msgSend_IntPtr (intptr,intptr,intptr)
at MonoTouch.StoreKit.SKPaymentQueue.AddPayment (MonoTouch.StoreKit.SKPayment payment) [0x00014] in /Developer/MonoTouch/Source/monotouch/src/StoreKit/.pp-SKPaymentQueue.g.cs:109
at IOS.Util.IAP.InAppPurchase.ReceivedResponse (MonoTouch.StoreKit.SKProductsRequest request, MonoTouch.StoreKit.SKProductsResponse response) [0x0001d] in /Users/aaron/Projects/budget-ease-xamarin/IOS/Util/IAP/InAppPurchase.cs:43
at at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0004c] in /Developer/MonoTouch/Source/monotouch/src/UIKit/.pp-UIApplication.cs:38
at IOS.Application.Main (System.String[] args) [0x00008] in /Users/aaron/Projects/budget-ease-xamarin/IOS/Main.cs:16
What's happened here is that the C# instance of your CustomPaymentObserver got garbage collected, while it's native ("Objective-C") counterpart lived on. When a notification was finally delivered, the native object tried to call into the now dead C# object and crashed your App.
To circumvent this, keep a reference to your CustomPaymentObserver e.g. in your AppDelegate to keep it alive.
I'm not sure this is documented somewhere for Xamarin.iOS (couldn't find something on a quick look), but I believe very similar for Xamarin.Droid (e.g. http://developer.xamarin.com/guides/android/advanced_topics/garbage_collection/)
I'm not really sure what was causing this. I thought it was perhaps something related to the linker. But I uninstalled Xamarin completely from my Mac (including all the MonoTouch stuff) and reinstalled everything and now it's working.

nhibernate CurrentSessionContext.Hasbind giving object reference not set

Hi i m using WebApi Mvc4 framework .net 4.0
I create a sessionFactory as follows:
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>();
}
and below when I am binding my ISession object to the HTTP context, I am getting error "Object reference not set"
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();
}
The error is at at line: CurrentSessionContext.HasBind(sessionFactory)
The error details are:
[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
I read so many posts, but no avail.
I have a MessageHandler (invoked by ninject), which invokes ISession, when I comment it out, the problem goes away. Why?
GlobalConfiguration.Configuration.MessageHandlers.Add(kernel.Get());
Your Factory and Session interfaces are not bound correctly. You have to set the scope as part of the Binding (InSingletonScope for the Factory as you only ever need one of these, and InThreadScope for the Session). This is so Ninject knows when to inject an existing reference or create a new instance of each type.
Try modifying your configuration to the following:
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();
}
To test the above you can immediately try to instantiate a Factory:
var sessionFactory = Kernel.Get<ISessionFactory>();

Resources