简体   繁体   English

Signalr集线器单例中的依赖注入

[英]Dependency injection in Signalr hub singleton

I use Ninject for dependency injection and I have something like this: 我使用Ninject进行依赖项注入,我有这样的东西:

    private IUnitOfWork unitOfWork;

    public ChatHub(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }

But the problem is that Hub is a singleton and creation of UnitOfWork is done only once which means I use the same UnitOfWork object the whole time. 但是问题在于Hub是一个单例,仅创建一次UnitOfWork,这意味着我始终使用相同的UnitOfWork对象。 Its not like in controllers which are created every time when the request come, so the scope of UnitOfWork is also per request. 它与每次请求到来时都会创建的控制器不同,因此UnitOfWork的范围也是针对每个请求的。

My question is can I set that unitOfWork gets instantiated and disposed for every reqesut to Hub, although Hub is singleton? 我的问题是,尽管集线器是单例的,我是否可以设置为实例化和分配给集线器的每个要求的unitOfWork?

you could try: 您可以尝试:

public interface IUnitOfWorkFactory
{
    IUnitOfWork Create();
}

public class UnitOfWorkFactory : IUnitOfWorkFactory
{
    public IUnitOfWork Create()
    {
        // creation of the unit of work
        return new UnitOfWork();
    }
}

In your hub: 在您的中心:

using (var unitOfWork = this.unitOfWorkFactory.Create())
{
    // use it here
    // i'm assuming that your unit of work implements IDisposable
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM