質問

I'm trying to use Autofac OnActivated to create a class

Along the lines of

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 has a ctor like:

public MyOtherThing(IMyThing myThing)

However, it's not firing

MyOtherThing never gets instantiated

What am I doing wrong?

役に立ちましたか?

解決

I'm not sure why your OnActivated isn't happening, but you could do this instead:

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

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

I think using AutoActivate has clearer intent then your style.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top