0

I want to unregister all service instances of SimpleIoC.

CODE

 public class IoCRegistry
   {
        private List<Type> RegistryList = new List<Type>();

        public void Register<TInterface, TClass>() where TInterface : class where TClass : class, TInterface
        {
            SimpleIoc.Default.Register<TInterface, TClass>();
            RegistryList.Add(typeof(TInterface));
        }

        public void UnregisterAll()
        {
            foreach (var item in RegistryList)
            {
                try
                {
                   var sdss = SimpleIoc.Default.GetAllInstances(item);

                    foreach (var instance in SimpleIoc.Default.GetAllInstances(item))
                    {
                       SimpleIoc.Default.Unregister(instance);
                    }
                 }
                 catch (Exception ex) { }
            }
        }
 }

Here SimpleIoc.Default.Unregister(instance); is not removing instance because when I try to locate the service and check its instance, it still has older instance.

Steven
  • 166,672
  • 24
  • 332
  • 435
TheDeveloper
  • 1,127
  • 1
  • 18
  • 55

1 Answers1

0

If you see the code Reset is what you are looking for, it will remove all registrations and previous instances, i.e. clear all lookups that the IoC have.

SimpleIoc.Default.Reset();

Your code isn't working because that clear only the cache instance of the registration as you can see here in the code.

/// <summary>
/// Removes the given instance from the cache. The class itself remains
/// registered and can be used to create other instances.
/// </summary>
/// <typeparam name="TClass">The type of the instance to be removed.</typeparam>
/// <param name="instance">The instance that must be removed.</param>
public void Unregister<TClass>(TClass instance)
    where TClass : class

If you want to do that one type by one you'd have to use:

/// <summary>
/// Unregisters a class from the cache and removes all the previously
/// created instances.
/// </summary>
/// <typeparam name="TClass">The class that must be removed.</typeparam>
[SuppressMessage(
    "Microsoft.Design",
    "CA1004",
    Justification = "This syntax is better than the alternatives.")]
public void Unregister<TClass>()
    where TClass : class

HIH

fmaccaroni
  • 3,846
  • 1
  • 20
  • 35
  • Reset will also unregister the services along with its instances, I want to keep registrations and just remove the instances for those services. – TheDeveloper Feb 25 '20 at 19:55
  • oh well, it's wierd because you're using the correct method then. How are you checking if it's the same instance as before unregistering? – fmaccaroni Feb 26 '20 at 13:51