Frage

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?

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top