/// <summary> /// The simplest way to call a method to set a value on a component /// is to use a lambda expression component and handle the method /// call right in the activator: /// </summary> public static void MethodInjection() { Console.WriteLine("\nPropertyandMethodInjection.MethodInjection:\n"); ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType <TheDependency>(); builder.Register(c => { MyObjectType myObjectType = new MyObjectType(); TheDependency dep = c.Resolve <TheDependency>(); myObjectType.SetTheDependency(dep); return(myObjectType); }); IContainer container = builder.Build(); using (ILifetimeScope lifetimeScope = container.BeginLifetimeScope()) { MyObjectType instance = lifetimeScope.Resolve <MyObjectType>(); Console.WriteLine("instance.GetType(): " + instance.GetType()); } }
/// <summary> /// If you can’t use a registration lambda, you can add an activating event handler: /// </summary> public static void ActivatingEventHandler() { Console.WriteLine("\nPropertyandMethodInjection.ActivatingEventHandler:\n"); ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType <TheDependency>(); builder .RegisterType <MyObjectType>() .OnActivating(e => { TheDependency dep = e.Context.Resolve <TheDependency>(); e.Instance.SetTheDependency(dep); }); IContainer container = builder.Build(); using (ILifetimeScope lifetimeScope = container.BeginLifetimeScope()) { MyObjectType instance = lifetimeScope.Resolve <MyObjectType>(); Console.WriteLine("instance.GetType(): " + instance.GetType()); } }