gpt4 book ai didi

c# - SignalR - Multi-Tenancy 依赖注入(inject)

转载 作者:太空宇宙 更新时间:2023-11-03 10:26:14 25 4
gpt4 key购买 nike

我需要根据租户的 owin 值解析 DbContext。但是在 hub 方法 OnDisconnected 的管道中,HttpContext 是 not accessible .

我的中心类:

public class UserTrackingHub : Hub
{
private readonly UserContext _context;

public UserTrackingHub(UserContext context) { ... }

public override async Task OnConnected() { /* OK HERE...*/ }

public override async Task OnDisconnected(bool stopCalled)
{
// NEVER FIRES WITH IF I USE THE CTOR INJECTION.

var connection = await _context.Connections.FindAsync(Context.ConnectionId);
if (connection != null)
{
_context.Connections.Remove(connection);
await _context.SaveChangesAsync();
}
}
}

这是我的 Autofac 配置:

    public static IContainer Register(IAppBuilder app)
{
var builder = new ContainerBuilder();

// Other registers...

builder.Register<UserContext>(c =>
{
// Details and conditions omitted for brevity.

var context = HttpContext.Current; // NULL in OnDisconnected pipeline.
var owinContext = context.GetOwinContext();
var tenant = owinContext.Environment["app.tenant"].ToString();
var connection = GetConnectionString(tenant);

return new UserContext(connection);
});

var container = builder.Build();
var config = new HubConfiguration
{
Resolver = new AutofacDependencyResolver(container)
};

app.MapSignalR(config);

return container;
}

有人可以帮助我以这种方式或任何其他方式识别租户 OnDisconnected 吗?
谢谢!

最佳答案

对于任何感兴趣的人,我最终注入(inject)了一个上下文工厂而不是上下文本身:

public class UserTrackingHub : Hub
{
private readonly Func<string, UserContext> _contextFactory;

public UserTrackingHub(Func<string, UserContext> contextFactory) { ... }

public override async Task OnConnected() { ... }

public override async Task OnDisconnected(bool stopCalled)
{
var tenant = Context.Request.Cookies["app.tenant"].Value;

using (var context = _contextFactory.Invoke(tenant))
{
var connection = await context.Connections.FindAsync(Context.ConnectionId);
if (connection != null)
{
context.Connections.Remove(connection);
await context.SaveChangesAsync();
}
}
}
}

和Autofac的配置:

 // Resolve context based on tenant
builder.Register<Func<string, UserContext>>(c => new Func<string, UserContext>(tenant => UserContextResolver.Resolve(tenant)));

关于c# - SignalR - Multi-Tenancy 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31527034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com