我有一个使用实体框架、SignalR 和 Hangfire 作业的 ASP.NET MVC 项目。
我的主(根)容器是这样定义的:
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 集线器以这种方式实例化(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:
经过思考(和睡过头),我想我有两个选择。我仍然想保留“每个请求的会话”(“每个集线器的会话”,“每个作业的会话”)。
选项1:
更改所有服务都将具有 InstancePerLifetimeScope。服务的实例化并不昂贵。对于维护某种状态的服务,我将创建另一个“存储”(类),它将是 SingleInstance 并且不会依赖于会话(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。你怎么看?
非常感谢!