【问题标题】:SignalR - structure Constructor dependency injection : signalr structuremap resolverSignalR - 结构构造函数依赖注入:signalr structuremap resolver
【发布时间】:2014-03-28 11:38:11
【问题描述】:

我在 MVC4 中使用结构映射构造函数依赖解析器。应用程序运行成功,但在 signalR javascript 客户端未连接到我的集线器(对象引用未设置为对象的实例。)

请告诉我下面的代码有什么问题:

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);
    }
}

但在运行应用程序时出错:

在 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) 

在网络中获取请求错误

<!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)
-->

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 signalr structuremap


    【解决方案1】:

    试试这个代码,如有必要,根据您的需要进行更改:

    [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());
            }   
        }
    }
    

    如有任何疑问,请给我留言。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 2018-06-17
      相关资源
      最近更新 更多