Autofac OnActivated不工作/呼叫

时间:2014-02-13 15:15:58

标签: inversion-of-control autofac

我正在尝试使用Autofac OnActivated创建一个类

沿着

的路线
builder.Register(c => new MyThing(c.Resolve<MyOtherThingDependancy>()))
    .As<IMyThing>()
    .SingleInstance()
    .OnActivated(c=> new MyOtherThing(c.Instance)); // i only need this to be instantiated once

MyOtherThing有一个像:

public MyOtherThing(IMyThing myThing)

然而,它没有解雇

MyOtherThing永远不会被实例化

我做错了什么?

1 个答案:

答案 0 :(得分:4)

我不确定为什么你的OnActivated没有发生,但你可以这样做:

builder.Register(c => new MyThing(c.Resolve<MyOtherThingDependancy>()))
    .As<IMyThing>()
    .SingleInstance()

builder.RegisterType<MyOtherThing>().AutoActivate();

我认为使用AutoActivate比你的风格有更清晰的意图。