如何在SignalI集线器的Unity IoC容器中注入依赖项? [英] How to Inject dependencies in a Unity IoC container for SignalR hub?

查看:108
本文介绍了如何在SignalI集线器的Unity IoC容器中注入依赖项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET MVC 5框架的顶部有一个用c#编写的应用程序.我在项目中实现了 Unity.Mvc .现在,我尝试将依赖项对象注入我的

I have an application that is written with c# on the top of the ASP.NET MVC 5 Framework. I implemented Unity.Mvc into my project. Now, I am trying to inject dependencies objects into my SignalR Hub.

我创建了一个名为 UnityHubActivator

我的课看起来像这样

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 类中,将以下内容添加到我的 RegisterTypes 方法

Then in my UnityConfig class I added the following to my RegisterTypes method

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

}

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

But when I run the hub, the constructor never get called and the connection never takes place.

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

How can I correctly use Unity framework to inject dependencies into my hub?

已更新

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

I tried to created a custom container like so

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

这就是我在Startup类中配置集线器的方式

Then here is how I configured the hub in the Startup 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);
        });
    }
}

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

But still now working... the hub constructor never get called.

这是我从客户端给我的集线器打电话的方式

Here is how I am calling my hub from the client

<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 看起来准确.

The UnitySignalRDependencyResolver appears accurate for that container.

摘自官方文档

SignalR中的依赖项注入

尝试以下示例来配置启动

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 ),因为容器需要了解对象图才能解决必要的依赖关系.

Make sure to register the necessary objects, including the hub (ChatHub) with the container as the container needs to know the object graph in order to resolve the necessary dependencies.

这篇关于如何在SignalI集线器的Unity IoC容器中注入依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆