Question

I am using structuremap constructor dependecy resolver in MVC4. application running successfully but in signalR javascript client is not connecting to my hub (Object reference not set to an instance of an object.)

Please tell me what's wrong with my codes below:

SignalRStructureMapResolver.cs

public class SignalRStructureMapResolver : DefaultDependencyResolver
{
    private readonly IContainer _container;

    public SignalRStructureMapResolver(IContainer container)
    {
        _container = container;
    }

    public override object GetService(Type serviceType)
    {
        object service;
        if (!serviceType.IsAbstract && !serviceType.IsInterface && serviceType.IsClass)
        {
            // Concrete type resolution
            service = _container.GetInstance(serviceType);
        }
        else
        {
            // Other type resolution with base fallback
            service = _container.TryGetInstance(serviceType) ?? base.GetService(serviceType);
        }
        return service;
    }

    public override IEnumerable<object> GetServices(Type serviceType)
    {
        var objects = _container.GetAllInstances(serviceType).Cast<object>();
        return objects.Concat(base.GetServices(serviceType));
    }
}

UiRegistry.cs

public class UiRegistry : Registry
{
    public UiRegistry()
    {
        Scan(x =>
            {
                x.TheCallingAssembly();
                x.WithDefaultConventions();
                x.AssemblyContainingType<IMappingEngine>();
            });

        KeepAlive.Start();

        For<IUnitOfWork>()
            .Singleton()
            .HybridHttpOrThreadLocalScoped()
            .Use<UnitOfWork>();

        For<IMappingEngine>().Use(ctx => Mapper.Engine);

        For<IDependencyResolver>().Add<SignalRStructureMapResolver>();
    }
}

AppStartUpModule.cs

public class AppStartUpModule : IHttpModule
{
    public static void BootStrapper()
    {
        ConfigureSignalR();            
    }


    private static void ConfigureSignalR()
    {
        GlobalHost.DependencyResolver = ObjectFactory.GetInstance<IDependencyResolver>();         
    }      
}

ChatHub.cs

public class ChatHub : Hub
{
    private readonly IViewRepository<MemberView> _memberRepository;
    public ChatHub(IViewRepository<MemberView> memberRepository)
    {
        _memberRepository = memberRepository;
    }

    public void Send(string message)
    {
        var name = HttpContext.Current.User.Identity.Name;

        var mem = _memberRepository.GetByKey(Property.Of<MemberView>(x => x.Code), name);

        var currentDateTime = SystemTime.Now();
        Clients.All.sendMessage(name, message, currentDateTime);
    }
}

But got at error when run application :

In Console of chrome

GET http://localhost:9095/signalr/negotiate?connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&clientProtocol=1.3&_=1392969587574 500 (Internal Server Error) 

In Network get request error

<!DOCTYPE html>
<html>
<head>
    <title>Object reference not set to an instance of an object.</title>
    <meta name="viewport" content="width=device-width" />
    <style>
     body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
     p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
     b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
     H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
     H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
     pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
     .marker {font-weight: bold; color: black;text-decoration: none;}
     .version {color: gray;}
     .error {margin-bottom: 10px;}
     .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
     @media screen and (max-width: 639px) {
      pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
     }
     @media screen and (max-width: 479px) {
      pre { width: 280px; }
     }
    </style>
</head>

<body bgcolor="white">

        <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>

        <h2> <i>Object reference not set to an instance of an object.</i> </h2></span>

        <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

        <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

        <br><br>

        <b> Exception Details: </b>System.NullReferenceException: Object reference not set to an instance of an object.<br><br>

        <b>Source Error:</b> <br><br>

        <table width=100% bgcolor="#ffffcc">
           <tr>
              <td>
                  <code>

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>

              </td>
           </tr>
        </table>

        <br>

        <b>Stack Trace:</b> <br><br>

        <table width=100% bgcolor="#ffffcc">
           <tr>
              <td>
                  <code><pre>

[NullReferenceException: Object reference not set to an instance of an object.]
Microsoft.AspNet.SignalR.PersistentConnection.ProcessNegotiationRequest(HostContext context) +400
Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(HostContext context) +318
Microsoft.AspNet.SignalR.Hubs.HubDispatcher.ProcessRequest(HostContext context) +526
Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(IDictionary`2 environment) +222
Microsoft.AspNet.SignalR.Owin.Middleware.HubDispatcherMiddleware.Invoke(IOwinContext context) +249
Microsoft.Owin.Mapping.&lt;Invoke&gt;d__0.MoveNext() +523
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +22
Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +33
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +150

 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +42
 System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415
 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +155
</pre></code>

              </td>
           </tr>
        </table>

        <br>

        <hr width=100% size=1 color=silver>

        <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34009

        </font>

</body>
</html>
<!-- 
[NullReferenceException]: Object reference not set to an instance of an object.
at Microsoft.AspNet.SignalR.PersistentConnection.ProcessNegotiationRequest(HostContext context)
at Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(HostContext context)
at Microsoft.AspNet.SignalR.Hubs.HubDispatcher.ProcessRequest(HostContext context)
at Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(IDictionary`2 environment)
at Microsoft.AspNet.SignalR.Owin.Middleware.HubDispatcherMiddleware.Invoke(IOwinContext context)
at Microsoft.Owin.Mapping.MapMiddleware.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow()
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)
at     Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
Was it helpful?

Solution

Try this code, If necessary make changes as per your need :

[assembly: OwinStartup(typeof(WebApp.Initialization.OwinStartup))]
namespace WebApp.Initialization
{
    public class OwinStartup
    {
        public static IBus Bus { get; private set; }

        public void Configuration(IAppBuilder app)
        {
            BootStrapper();

            var resolver = ObjectFactory.GetInstance<IDependencyResolver>();

            var config = new HubConfiguration
            {
                Resolver = resolver
            };

            app.MapSignalR(config);
        }           

        public static void ConfigureNServiceBus()
        {
            Bus = Configure.With()
                .StructureMapBuilder(ObjectFactory.Container)
                .MsmqSubscriptionStorage()
                .PurgeOnStartup(false)
                .UnicastBus()
                .ImpersonateSender(false)
                .CreateBus()
                .Start(() => Configure.Instance.ForInstallationOn<NServiceBus.Installation.Environments.Windows>().Install());
        }   
    }
}

If any query, post me. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top