简体   繁体   中英

Autofac - passing a value inside a .OnActivated Method at the Resolve time

i need to pass a value inside .OnActivated method when i resolve an instance

builder.RegisterType<MyType>().PropertiesAutowired().
    .OnActivated(x => {                    
        var myValue  =    //i need to get a value passed when i call Resolve
        //do stuffs
        }
    );

var myObject = scope.Resolve<MyType>();   //<--to pass a value here

how to do this? i know that exist factories? does it exist a simplier way

You have two main cases:

1/Your value is static application wide

You can simply register like this

int dummy = 20;

builder.RegisterType<MyType>().PropertiesAutowired()
.OnActivated(x => 
{
    var myValue = dummy;
} 

This is perfectly valid

2/You parameter is known at resolve time only

You can add your parameter as a constructor argument:

public class MyType
{
    private int intValue;

    public MyType(int myCustomValue)
    {
        this.intValue = myCustomValue;
    }
}

Then you can either build a small Abstract Factory or use built int Func

int dummy = 20;
var myObjectFactory = scope.Resolve<Func<int, MyType>>();

var myObject = myObjectFactory(dummy);

Delegate Factories can also help

If the value you need to pass is a value that is being calculated on resolve time, from inside the container. You can use the IActivatedEventArgs .

The e.Instance is an object related to the registered object ( MyType in the code below), you can do what ever you want with it.

.OnActivated((IActivatedEventArgs<MyType> e) =>
    {
        MyChild myChild = e.Context.Resolve<MyChild>();
        //If you has a SetChild method inside MyType class you can now use it.
        e.Instance.SetChild(myChild);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM