gpt4 book ai didi

asp.net-mvc - Autofac (+MVC + EF + SignalR + Hangfire) 生命周期范围

转载 作者:行者123 更新时间:2023-12-02 01:52:31 25 4
gpt4 key购买 nike

我有一个 ASP.NET MVC 项目,它使用 Entity Framwork、SignalR 和 Hangfire 作业。

我的主(根)容器是这样定义的:

builder.RegisterType<DbContext>().InstancePerLifetimeScope(); // EF Db Context
builder.RegisterType<ChatService>().As<IChatService>().SingleInstance(); // classic "service", has dependency on DbContext
builder.RegisterType<ChatHub>().ExternallyOwned(); // SignalR hub
builder.RegisterType<UpdateStatusesJob>().InstancePerDependency(); // Hangfire job
builder.RegisterType<HomeController>().InstancePerRequest(); // ASP.NET MVC controller
IContainer container = builder.Build();

对于 MVC,我使用 Autofac.MVC5 nuget 包。依赖解析器:

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

对于 SignalR,我使用 Autofac.SignalR nuget 包。依赖解析器:

GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);

我的 signalR hub 是这样实例化的 ( http://autofac.readthedocs.org/en/latest/integration/signalr.html#managing-dependency-lifetimes ):

private ILifetimeScope _hubScope;
protected IChatService ChatService;
public ChatHub(ILifetimeScope scope) {
_hubScope = scope.BeginLifetimeScope(); // scope
ChatService = _hubScope.Resolve<IChatService>(); // this service is used in hub methods
}
protected override void Dispose(bool disposing)
{
// Dipose the hub lifetime scope when the hub is disposed.
if (disposing && _hubScope != null)
{
_hubScope.Dispose();
}
base.Dispose(disposing);
}

对于 Hangfire,我使用 Hangfire.Autofac 包:

config.UseActivator(new AutofacJobActivator(container));

作业的实例化方式如下:

private readonly ILifetimeScope _jobScope;
protected IChatService ChatService;
protected BaseJob(ILifetimeScope scope)
{
_jobScope = scope.BeginLifetimeScope();
ChatService = _jobScope.Resolve<IChatService>();
}
public void Dispose()
{
_jobScope.Dispose();
}

疑问/问题:我总是在集线器和作业中获得相同的 DbContext 实例。我希望所有集线器实例都将获得相同的 ChatService,但 DbContext (它是 ChatService 的依赖项)将始终是一个新实例。 Hangfire 工作也应该表现相同。

这可以完成吗,还是我错过了什么?

更新1:

经过思考(并睡了一觉),我想我有两个选择。我仍然想保留“每个请求的 session ”(“每个集线器的 session ”,“每个作业的 session ”)。

选项 1:

更改为所有服务都将具有 InstancePerLifetimeScope。服务的实例化并不昂贵。对于维护某种状态的服务,我将创建另一个“存储”(类),它将是 SingleInstance 并且不依赖于 session (DbContext)。我认为这也适用于枢纽和工作。

选项 2:

创建@Ric .Net 建议的某种工厂。像这样的事情:

public class DbFactory: IDbFactory
{
public MyDbContext GetDb()
{
if (HttpContext.Current != null)
{
var db = HttpContext.Current.Items["db"] as MyDbContext;
if (db == null)
{
db = new MyDbContext();
HttpContext.Current.Items["db"] = db;
}
return db;
}

// What to do for jobs and hubs?
return new MyDbContext();
}
}

protected void Application_EndRequest(object sender, EventArgs e)
{
var db = HttpContext.Current.Items["db"] as MyDbContext;
if (db != null)
{
db.Dispose();
}
}

我认为这适用于 MVC,但我不知道让它适用于集线器(每个集线器调用都是集线器的新实例)和作业(作业的每次运行都是集线器的新实例)工作类别)。

我倾向于选项 1。你觉得怎么样?

非常感谢!

最佳答案

我对 AutoFac 完全没有经验。但引起我注意的是:

I want that all hub instances will get the same ChatService, but the DbContext (which is dependency of ChatService) will always be a new instance.

您在这里所说的基本上是:

“我的车由同一家汽车公司进行维护,该公司依赖于他们的车库,但每次我带车时,我都希望车库是新的”。

当您在其他组件中注入(inject)(完全构建实例,包括其依赖项)ChatService时,当然它所具有的其他依赖项也会被构建,无论它们是否有其他类型的生活方式。当创建一个生命周期比所注入(inject)的对象短的对象时,您就创建了一个所谓的“captive dependency”。 '

ChatService 中获取 DbContext 的新“实例”的唯一方法不是注入(inject) DbContext 本身,而是通过注入(inject)一个 DbContextFactory,它会在您使用时为您创建 DbContext

实现看起来像这样:

public class DbContextFactory
{
public DbContext Create()
{
return new DbContext();
}
}

//usage:
public class ChatService
{
private readonly DbContextFactory dbContextFactory;

public ChatService(DbContextFactory dbContextFactory)
{
this.dbContextFactory = dbContextFactory;
}

public void SomeMethodInChatService()
{
using (var db = this.dbContextFactory.Create())
{
//do something with DbContext
}
}
}

可以使用 Singleton Lifestyle 在 AutoFac 中注册 DbContextFactory

但这可能不是您的目标。因为在这种情况下,每次使用DbContext都会得到一个新的。另一方面,新的 DbContext 可能是解决此问题的最安全方法,您可以阅读 here .

这个伟大的答案值得一读,原因不止一个,因为它解释了如何使用 command / handler pattern这应该非常适合你的情况。

这将使您的聊天服务完全不知道DbContext,从而改进了' SOLID ' 设计您的应用程序并创建测试 ChatService 的可能性,这在直接注入(inject) DbContextDbContextFactory 时实际上是不可撤销的。

关于asp.net-mvc - Autofac (+MVC + EF + SignalR + Hangfire) 生命周期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29086173/

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