【发布时间】:2012-03-22 04:49:01
【问题描述】:
我应该指出,我对 Castle 比较陌生,所以还不知道我在用它做什么。要点是,我正在尝试使用 Castle Windsor 制作对象的自定义生命周期。我不完全确定应该如何做到这一点,但是,我能找到的最接近它应该如何工作的近似值我在下面详细说明。
我想要一个单例,但我无法释放此类型并为其分配新实例。
即,
public interface IMyObject { string text; }
public class MyObject() : IMyObject {
public string text;
}
var container = new WindsorContainer();
container.Register(Component.For<IMyObject>().ImplementedBy<MyObject>().LifeStyle.Singleton);
MyObject item = SomeMethodGetInstance(); //Defines scope for instance 1
item = container.Resolve<IMyObject>(item);
Print(item);
>>instance 1
....
item = container.Resolve<IMyObject>(); //gets instance 1
Print(item);
>>instance 1
....
item = SomeMethodGetInstance() //New scope defined, now using instance 2
我希望能够释放该实例,但 Windsors 对 Singleton 的定义对于我的需求来说过于死板。
container.Release(item); //I need to release the current instance, this doesn't work.
或
container.Kernal.ReleaseComponent(item); //Don't work either.
因此,当我将新项目设置为当前项目时,它不会恢复为实例 1。
item = container.Resolve<IMyObject>(item); //sets the currect instance of MyObject
Print(item);
>>instance 2
我需要存储一个具有自定义作用域的变量,Singleton 或 Transient 都不会为我解决问题。当存储的变量进出范围时,我需要能够定义范围。
更重要的是,如果我有另一个类B,它依赖于A,那么如果我从容器外部获取A,我如何在容器中设置A?这在单例场景中很好,但我无法为瞬态场景设置它,但是,对于单例,一旦设置,我就无法释放它,这是必要的。
请问我该怎么做?
我想在代码中而不是在 xml 中执行此操作,因为我正在动态注册类。
【问题讨论】:
-
您可以根据自己的要求创建自定义生活方式。请参阅此处的示例:stackoverflow.com/a/1366597/1275399
标签: c# .net dependency-injection castle-windsor