unitycontainer / microsoft-dependency-injection

Unity.Microsoft.DependencyInjection package
Apache License 2.0
63 stars 36 forks source link

Provide an event for CreateChildContainer #76

Closed rizi closed 4 years ago

rizi commented 4 years ago

Hi, Is there a way to subscribe to an event when a child container is created or any other way to get notified? We need to subscribe to this event and add some custom UnityContainerExtension.

br

ENikS commented 4 years ago

This event will be fired when child container is created.

rizi commented 4 years ago

@ENikS thx for the fast reply, can you tell me how to subscribe to this event, I can't find a proper way, the only usage of ExtensionContext seems to be in the ContainerContext (https://github.com/unitycontainer/container/blob/b737bb32f17c39b174103aae86b63b95b302636a/src/UnityContainer.ContainerContext.cs), but that's a private class.

So it seems I can't find a hook to register to this event.

br

ENikS commented 4 years ago

You need to create an Unity Extension, add it to the container and handle the event from your extension.

rizi commented 4 years ago

You need to create an Unity Extension, add it to the container and handle the event from your extension.

thx, in case someone needs a reference implementation:

  //register the custom extension
   IUnityContainer container = new UnityContainer();
   EventSubscriptionUnityContainerExtension extension = container.Configure<EventSubscriptionUnityContainerExtension >();

      if (extension == null)
             container.AddNewExtension<EventSubscriptionUnityContainerExtension >();

    //custom extension
    public class EventSubscriptionUnityContainerExtension : UnityContainerExtension
    {

        /// <inheritdoc />
        protected override void Initialize()
        {
            Context.ChildContainerCreated += OnChildContainerCreated;
        }

        private void OnChildContainerCreated(object sender, ChildContainerCreatedEventArgs e)
        {
            //do whatever you want here, btw. Container (UnityContainer) is available here as well.
        }
    }