如何在 SignalR hub 的 Unity IoC 容器中注入依赖项?

How to Inject dependencies in a Unity IoC container for SignalR hub?

我有一个在 ASP.NET MVC 5 框架之上用 c# 编写的应用程序。我实现了 Unity.Mvc into my project. Now, I am trying to inject dependencies objects into my SignalR Hub.

我创建了一个名为 UnityHubActivator

的 class

我的class看起来像这样

public class UnityHubActivator : IHubActivator
{
    private readonly IUnityContainer _container;

    public UnityHubActivator(IUnityContainer container)
    {
        _container = container;
    }

    public IHub Create(HubDescriptor descriptor)
    {
        return (IHub)_container.Resolve(descriptor.HubType);
    }
}

然后在我的 UnityConfig class 中,我将以下内容添加到我的 RegisterTypes 方法中

var unityHubActivator = new UnityHubActivator(container);

container.RegisterInstance<IHubActivator>(unityHubActivator);

我的集线器是这样的

[Authorize]
public class ChatHub : Hub
{
    protected IUnitOfWork UnitOfWork { get; set; }

    public ChatHub(IUnitOfWork unitOfWork)
        : base()
    {
        UnitOfWork = unitOfWork;
    }

}

但是当我 运行 集线器时,构造函数永远不会被调用,连接也永远不会发生。

如何正确使用 Unity 框架将依赖项注入我的集线器?

已更新

我试过像这样创建一个自定义容器

public class UnitySignalRDependencyResolver: DefaultDependencyResolver
{
    protected IUnityContainer Container;
    private bool IsDisposed = false;

    public UnitySignalRDependencyResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }

        Container = container.CreateChildContainer();
    }

    public override object GetService(Type serviceType)
    {
        if (Container.IsRegistered(serviceType))
        {
            return Container.Resolve(serviceType);
        }

        return base.GetService(serviceType);
    }

    public override IEnumerable<object> GetServices(Type serviceType)
    {
        if (Container.IsRegistered(serviceType))
        {
            return Container.ResolveAll(serviceType);
        }

        return base.GetServices(serviceType);
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

        if(IsDisposed)
        {
            return;
        }

        if(disposing)
        {
            Container.Dispose();
        }

        IsDisposed = true;
    }
} 

这就是我在启动时配置集线器的方式 class

public class Startup
{
    public IUnityContainer Container { get; set; }
    public Startup(IUnityContainer container)
    {
        Container = container;
    }

    public void Configuration(IAppBuilder app)
    {
        app.Map("/signalr", map =>
        {
            var resolver = new UnitySignalRDependencyResolver(Container);

            var hubConfiguration = new HubConfiguration
            {
                Resolver = resolver
            };

            map.RunSignalR(hubConfiguration);
        });
    }
}

但现在仍在工作...永远不会调用集线器构造函数。

这是我从客户端调用集线器的方式

<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>

$(function () {
    // Reference the auto-generated proxy for the hub.
    var app = $.connection.chatHub;
    console.log('Getting things ready....');

    app.client.outOfTasks = function () {
        console.log('Nothing to do here')
    };

    app.client.logError = function (message) {
        console.log(message)
    };

    app.client.logNote = function (message) {
        console.log(message)
    };

    app.client.assignTask = function (taskId) {
        app.server.taskReceived();
        console.log('task received!!!' + taskId);

    };

    // Start the connection.
    $.connection.hub.start().done(function () {
        console.log('Connection Started....');
    });
});

</script>

该容器的 UnitySignalRDependencyResolver 看起来是准确的。

摘自官方文档,

Dependency Injection in SignalR

尝试以下示例来配置 Startup

public class Startup{    
    public void Configuration(IAppBuilder app) {
        IUnityContainer container = GetContainer(); 

        var resolver = new UnitySignalRDependencyResolver(container);

        var config = new HubConfiguration {
            Resolver = resolver
        };      
        app.MapSignalR("/signalr", config);
    }

    IUnityContainer GetContainer() {
        //...call the unity config related code.
        var container = UnityConfig.Container;
        //...any other code to populate container.

        return container;
    }
}

确保向容器注册必要的对象,包括集线器 (ChatHub),因为容器需要知道对象图才能解析必要的依赖关系。