Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top