Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

c# - 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>();
}
}
question from:https://stackoverflow.com/questions/66060619/how-to-remove-a-component-from-castle-windsor-5-0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...