How to remove(unregister) registered instance from Unity mapping?

前端 未结 6 1860
野趣味
野趣味 2020-12-04 19:50

I meet one problem that i can\'t solve now. I have the following:

UnityHelper.DefaultContainer.RegisterInstance(typeof(IMyInterface), \"test\", instance);
         


        
6条回答
  •  半阙折子戏
    2020-12-04 20:26

    Here is how I handled unregistering instances from a unity container

    I needed to implement Add/Remove functionality like this:

    public interface IObjectBuilder
    {
        void AddInstance(T instance);
        void RemoveInstance(T instance);
    }
    

    I created a custom lifetime manager to do the implementation

    public class ExplicitLifetimeManager :
        LifetimeManager
    {
        object Value;
    
        public override object GetValue()
        {
            return Value;
        }
    
        public override void SetValue(object newValue)
        {
            Value = newValue;
        }
    
        public override void RemoveValue()
        {
            Value = null;
        }
    }
    

    Here is the final implementation:

        Dictionary Instances = new Dictionary();
    
        public void AddInstance(T instance)
        {
            ExplicitLifetimeManager e = new ExplicitLifetimeManager();
            Instances[instance] = e;
            Container.RegisterInstance(instance, e);
        }
    
        public void RemoveInstance(T instance)
        {
            Instances[instance].RemoveValue();
            Instances.Remove(instance);
        }
    

    calling removevalue on the custom lifetime manager causes the instance to be unregistered

提交回复
热议问题