【发布时间】:2023-12-28 17:13:01
【问题描述】:
我有一个在 ASP.NET MVC 5 框架之上用 c# 编写的应用程序。我在我的项目中实现了Unity.Mvc。现在,我正在尝试将依赖项对象注入我的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 方法中
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;
}
}
然后这是我在 Startup 类中配置集线器的方式
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>
【问题讨论】:
标签: c# dependency-injection asp.net-mvc-5 signalr unity-container