Autofac FactoryScoped Linq to SQL 数据上下文
使用 Linq to SQL 数据上下文注册 FactoryScoped
意味着什么?谁负责处置?
这是我看到的代码。对于 ASP.NET 应用程序,我认为不建议将 FactoryScoped
用于数据上下文?
builder.Register(c => new MyDataContext("connectionString"))
.As<MyDataContext>()
.FactoryScoped();
What does FactoryScoped
registration with a Linq to SQL data context mean? Who takes care of the disposing?
Here is the code I saw. For an ASP.NET application, I assume FactoryScoped
is not recommended for data contexts?
builder.Register(c => new MyDataContext("connectionString"))
.As<MyDataContext>()
.FactoryScoped();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1.x 中的
FactoryScoped
在 2.x 中被重命名为InstancePerDependency
,我认为这更好地描述了效果。这意味着每次注入服务时 Autofac 都会提供一个新实例。在您的情况下,将在注入时创建新的数据上下文。Autofac 仍然会负责处理,但这里存在一个陷阱。
MyDataContext
的每个实例都将在当前生命周期范围内进行跟踪,因此在释放范围之前不会被释放。要自行控制处置,您可以使用
ExternallyOwned
标记注册。您还可以查看Owned<>
类型。阅读确定性处置和自有实例。FactoryScoped
in 1.x is renamed in 2.x toInstancePerDependency
, which imo better describes the effect. It means that Autofac will serve up a new instance each time the service is injected. In your case a new data context will be created upon injection.Autofac will still take care of disposing, but herein lies the pitfall. Every instance of
MyDataContext
will be tracked in the current lifetime scope, and will thus not be freed until the scope is freed.To take control of disposal yourself you can tag the registration with
ExternallyOwned
. You could also look into theOwned<>
type. Read up on deterministic disposal and owned instances.