autofac实例初始化通知
有没有办法确定 Autofac 何时完成实例的初始化? 如果您有惰性依赖项,或者通过属性注入依赖项,您可能需要它。
可能的解决方案可能如下所示:
public class Component : IKeepMeInformed {
private readonly IOtherComponent otherComponent;
public class Component(Lazy<IOtherComponent> otherComponent) {
this.otherComponent = otherComponent;
}
void IKeepMeInformed.InitializationCompleted() {
// Do whatever you need with this.otherComponent.Value
}
}
Is there a way to determine when Autofac has completed an initialization of an instance?
You may need it if you have Lazy dependencies, or you inject dependencies via properties.
Possible solution might look like this:
public class Component : IKeepMeInformed {
private readonly IOtherComponent otherComponent;
public class Component(Lazy<IOtherComponent> otherComponent) {
this.otherComponent = otherComponent;
}
void IKeepMeInformed.InitializationCompleted() {
// Do whatever you need with this.otherComponent.Value
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不直接与 Lazy 组件相关,但 Autofac 公开了一些事件,可让您挂钩实例的生命周期。侦听OnActivated 事件将使您能够在实例启动后立即执行操作创建的。例如:
更新:实际上,在
Component
类的上下文中,您应该“知道”实例何时初始化。每当您首先访问 Lazy<>.Value 属性时都会出现这种情况。Not directly tied to Lazy components, but Autofac exposes events that lets you hook into the lifetime of instances. Listening for the OnActivated event will enable you to do stuff immediately after an instance have been created. E.g.:
Update: actually, in the context of your
Component
class, you should "know" when the instance is initialized. It will be whenever you access theLazy<>.Value
property first.