简体   繁体   中英

Dependency injection in Signalr hub singleton

I use Ninject for dependency injection and I have something like this:

    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. Its not like in controllers which are created every time when the request come, so the scope of UnitOfWork is also per request.

My question is can I set that unitOfWork gets instantiated and disposed for every reqesut to Hub, although Hub is singleton?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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