22

我在我的 MVC3 应用程序中使用 SignalR,并且由于我已经在我的控制器上实现了 StructureMap 依赖注入,我想在我的集线器中做同样的事情,但我似乎无法让它工作。

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

SignalRSmDependencyResolver.cs

public class SignalRSmDependencyResolver : DefaultDependencyResolver
{
    private IContainer _container;

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

    public override object GetService(Type serviceType)
    {
        object service = null;
        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>();
        objects.Concat(base.GetServices(serviceType));
        return objects;
    }
}

SignalRExtensionsRegistry.cs

public class SignalRExtensionsRegistry : Registry
{
    public SignalRExtensionsRegistry()
    {
        For<IDependencyResolver>().Add<SignalRSmDependencyResolver>();
    }
}

国际奥委会

public static class IoC {
    public static IContainer Initialize() {

        var container = BootStrapper.Initialize();

        container.Configure(x =>
        {
            x.For<IControllerActivator>().Singleton().Use<StructureMapControllerActivator>();
        });

        return container;
    }
}

public class StructureMapControllerActivator : IControllerActivator {
    public StructureMapControllerActivator(IContainer container) {
        _container = container;
    }

    private IContainer _container;

    public IController Create(RequestContext requestContext, Type controllerType) {
        IController controller = DependencyResolver.Current.GetService(controllerType) as IController;
        return controller;
    }
}

AppStart_Structuremap.cs

[assembly: WebActivator.PreApplicationStartMethod(typeof(StoreUI.AppStart_Structuremap), "Start")]

namespace MyNameSpace {
public static class AppStart_Structuremap {
    public static void Start() {
        var container = (IContainer) IoC.Initialize();
        DependencyResolver.SetResolver(new StructureMapDependenceyResolver(container));
        AspNetHost.SetResolver(new StructureMapDependencyResolver(container));            
    }
}
}

NotificationsHub.cs

[HubName("notificationsHub")]
public class NotificationsHub : Hub
{    
    #region Declarations
    private readonly IUserService userService;
    #endregion

    #region Constructor

    public NotificationsHub(IUserService userService)
    {
        this.userService = userService;
    }

    #endregion

    public void updateServer(string message)
    {
        Clients.updateClient(message);
    }
}

谢谢

4

4 回答 4

8

将 Structuremap 导入 SignalR 实际上非常容易。首先,您要创建自己的解析器:

StructureMap 解析器

用途:

using SignalR.Infrastructure;
using StructureMap;

班级:

public class StructureMapResolver : DefaultDependencyResolver
{
    private IContainer _container;

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

    public override object GetService(Type serviceType)
    {
        object service = null;
        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));
    }
}

这里的想法是尝试使用您的容器来解析依赖项,如果您没有连接依赖项,请将其传递给默认解析器。这样您就不必担心 SignalR 中的所有其他依赖项,并且可以只关注您想要注入的内容(Hubs、ConnectionIdFactory、MessageBus 等)。

解析器和集线器的绑定

接下来,您将要在您的容器中注册它(我喜欢使用注册表):

用途:

using SignalR.Infrastructure;
using StructureMap.Configuration.DSL;

班级:

public class ExtensionsRegistry : Registry
{
    public ExtensionsRegistry()
    {
        For<IDependencyResolver>().Add<StructureMapResolver>();
    }
}

解析器更换

最后,您将要告诉 SignalR 使用您的解析器而不是默认值:

Global::Application_Start 或 WebActivator::Pre_Start

用途:

using SignalR.Hosting.AspNet;
using SignalR.Infrastructure;

应用程序_开始:

// Make sure you build up the container first
AspNetHost.SetResolver(StructureMap.ObjectFactory.GetInstance<IDependencyResolver>());

具有注入依赖项的愚蠢集线器

现在您可以将您的容器知道的任何依赖项注入集线器本身:

[HubName("defaultHub")]
public class DefaultHub : Hub, IDisconnect
{
    private readonly IRepository _repo;
    public DefaultHub(IRepository repo)
    {
        _repo = repo;
    }

    public void Connect()
    {
        Caller.setUser(Context.ConnectionId);
        Clients.addMessage(string.Format("{0} has connected", Context.ConnectionId));
    }

    public void MessageSender(string message)
    {
        Caller.addMessage(_repo.RepositoryMessage());
        Clients.addMessage(message);
    }

    public Task Disconnect()
    {
        var clientId = this.Context.ConnectionId;
        return Task.Factory.StartNew(() => { Clients.addMessage(string.Format("{0} has disconnected", clientId)); });
    }
}
于 2012-03-26T03:49:47.997 回答
5

您是否按照此处的说明进行操作:- https://github.com/SignalR/SignalR/wiki/Extensibility

您将需要使用AspNetHost.SetResolver.

于 2012-03-23T05:22:44.473 回答
2

我知道这是一个旧线程,但是对于那些想知道新版本 signalR 中的 AspNetHost.SetResolver 在哪里的人,您可以在 App_Start StructuremapMvc.cs 中使用它:

    public static void Start() {
        IContainer container = IoC.Initialize();
        GlobalHost.DependencyResolver = new SignalRSmDependencyResolver(container); // for signalR

        DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
    }
于 2013-06-12T07:48:01.610 回答
1

Add something like this to a file in your App_Start folder. This code snippet is for Ninject, so just replace AspNetHost.SetResolver()

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Ninject;
using SignalR.Hosting.AspNet;
using SignalR.Infrastructure;
using SignalR.Ninject;
using Web.Models;

[assembly: WebActivator.PreApplicationStartMethod(typeof(Web.App_Start.NinjectSignalR), "Start")]

namespace Web.App_Start
{
    public static class NinjectSignalR
    {
        public static void Start()
        {
            IKernel kernel = CreateKernel();
            // switch this line to the structuremap resolver
            AspNetHost.SetResolver(new NinjectDependencyResolver(kernel));
        }

        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            RegisterServices(kernel);
            return kernel;
        }

        private static void RegisterServices(IKernel kernel)
        {
            // add your services here
            //kernel.Bind<IRepository>().To<Repository>();
        }
    }
}
于 2012-03-25T18:31:05.400 回答