简体   繁体   中英

How to remove a component from castle windsor 5.0

I am new to using Castle Windsor I have a couple of registered dependencies using Castle Windsor. I would like to dispose and remove one of these injected dependency at a particular time. How can I do this. My code is as follows: In the main function.

var container = new WindsorContainer();
 container.Register(Component.For<ILogger>().ImplementedBy<logger>());

Please not that this dependency is not resolved but its Injected using Constructor.

  public ILogger logger { get; set; } 
   public DoSomethin(
            ILogger logger)
        {
            this.logger = logger;
        }

Please Note that I am using castle windsor V5. The reason for doing this to clear the GC. Older versions have IKernel has a RemoveComponent method. which does not exists nowadays. Resolving component will be as follows:

    public static class helper 
    {
     public static T Resolve<T>()
        {
            return Instance.Resolve<T>();
        }
    }

Main class

public class Program{
    public static void Main()
{
var obj1 = helper.Resolve<logger>();
}
}

The two key principles of using Castle Windsor efficiently and safely from a memory perspective are to:

  1. Ensure that you register your components with an appropriate Lifestyle, and
  2. Ensure you Release everything you Resolve .

For example:

...
container.Register(Component.For<ILogger>().ImplementedBy<logger>().LifestyleTransient()));
...
var obj1 = container.Resolve<logger>();
...
container.Release(obj1)

If there is a component that is memory intensive and you want to ensure that memory is freed as soon as that component is no longer needed then you might consider using the Transient lifestyle. This decision should impact only the code that registers the components.

If you stick to the above rules you ensure that the all your code that uses the container does not need to understand anything about how they are constructed or the lifetime of the component.

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