- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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) DbContext
或 DbContextFactory
时实际上是不可撤销的。
关于asp.net-mvc - Autofac (+MVC + EF + SignalR + Hangfire) 生命周期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29086173/
我不能解决这个问题。和标题说的差不多…… 如果其他两个范围/列中有“否”,我如何获得范围或列的平均值? 换句话说,我想计算 A 列的平均值,并且我有两列询问是/否问题(B 列和 C 列)。我只希望 B
我知道 python 2to3 将所有 xrange 更改为 range 我没有发现任何问题。我的问题是关于它如何将 range(...) 更改为 list(range(...)) :它是愚蠢的,只是
我有一个 Primefaces JSF 项目,并且我的 Bean 注释有以下内容: @Named("reportTabBean") @SessionScoped public class Report
在 rails3 中,我在模型中制作了相同的范围。例如 class Common ?" , at) } end 我想将公共(public)范围拆分为 lib 中的模块。所以我试试这个。 module
我需要在另一个 View 范围 bean 中使用保存在 View 范围 bean 中的一些数据。 @ManagedBean @ViewScoped public class Attivita impl
为什么下面的代码输出4?谁能给我推荐一篇好文章来深入学习 javascript 范围。 这段代码返回4,但我不明白为什么? (function f(){ return f(); functio
我有一个与此结构类似的脚本 $(function(){ var someVariable; function doSomething(){ //here } $('#som
我刚刚开始学习 Jquery,但这些示例对我帮助不大...... 现在,以下代码发生的情况是,我有 4 个表单,我使用每个表单的链接在它们之间进行切换。但我不知道如何在第一个函数中获取变量“postO
为什么当我这样做时: function Dog(){ this.firstName = 'scrappy'; } Dog.firstName 未定义? 但是我可以这样做: Dog.firstNa
我想打印文本文件 text.txt 的选定部分,其中包含: tickme 1.1(no.3) lesson1-bases lesson2-advancedfurther para:using the
我正在编写一些 JavaScript 代码。我对这个关键字有点困惑。如何在 dataReceivedHandler 函数中访问 logger 变量? MyClass: { logger: nu
我有这个代码: Public Sub test() Dim Tgt As Range Set Tgt = Range("A1") End Sub 我想更改当前为“A1”的 Tgt 的引
我正忙于此工作,以为我会把它放在我们那里。 该数字必须是最多3个单位和最多5个小数位的数字,等等。 有效的 999.99999 99.9 9 0.99999 0 无效的 -0.1 999.123456
覆盖代码时: @Override public void open(ExecutionContext executionContext) { super.open(executio
我想使用 preg_match 来匹配数字 1 - 21。我如何使用 preg_match 来做到这一点?如果数字大于 21,我不想匹配任何东西。 example preg_match('([0-9]
根据docs range函数有四种形式: (range) 0 - 无穷大 (range end) 0 - 结束 (range start end)开始 - 结束 (range start end st
我知道有一个UISlider,但是有人已经制作了RangeSlider(用两个拇指吗?)或者知道如何扩展 uislider? 最佳答案 我认为你不能直接扩展 UISlider,你可能需要扩展 UICo
我正在尝试将范围转换为列表。 nums = [] for x in range (9000, 9004): nums.append(x) print nums 输出 [9000] [9
请注意:此问题是由于在运行我的修饰方法时使用了GraphQL解析器。这意味着this的范围为undefined。但是,该问题的基础知识对于装饰者遇到问题的任何人都是有用的。 这是我想使用的基本装饰器(
我正在尝试创建一个工具来从网页上抓取信息(是的,我有权限)。 到目前为止,我一直在使用 Node.js 结合 requests 和 Cheerio 来拉取页面,然后根据 CSS 选择器查找信息。我已经
我是一名优秀的程序员,十分优秀!