我正在使用 Castle Windsor 和 DynamicProxy 从头开始实现持久性延迟加载(我知道 NHibernate 可能是一个选项等)。我已经实现了一个自定义组件激活器来始终将我的业务类实例化为代理。我发现当从类本身内部调用类方法时,没有使用使用拦截器时自动创建的默认 mixin 代理,这是一个问题。所以我继承了 DefaultComponentActivator 并覆盖了 CreateInstance() 我正在调用 CreateClassProxy() 来获取一个从业务类继承的代理,这在这方面工作正常。
现在我希望我的这个 'ProxyComponentActivator' 激活器只被 Castle 实例化一次,但正在为每个类类型创建一个新实例。那是对的吗?
目前的注册是这样的:
public void Install(
IWindsorContainer container,
Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store) {
container.Register(
Classes
.FromAssemblyContaining(typeof(OneOfMyBusinessClasses))
.InNamespace(typeof(OneOfMyBusinessClasses).Namespace)
.WithService.DefaultInterfaces()
.Configure(reg => reg.Activator<ProxyComponentActivator>())
.LifestyleTransient(),
etc.
);
);
激活器实现如下:
public class ProxyComponentActivator : DefaultComponentActivator
{
protected Castle.DynamicProxy.ProxyGenerator ProxyGenerator { get; set; }
protected PersistenceInterceptor PersistenceInterceptor { get; set; }
public ProxyComponentActivator(ComponentModel model, Castle.MicroKernel.IKernelInternal kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
: base(model, kernel, onCreation, onDestruction)
{
this.ProxyGenerator = kernel.Resolve<Castle.DynamicProxy.ProxyGenerator>();
this.PersistenceInterceptor = kernel.Resolve<PersistenceInterceptor>();
}
protected override object CreateInstance(CreationContext context, ConstructorCandidate constructor, object[] arguments) //, Type[] signature)
{
object instance;
Type implType = this.Model.Implementation;
ProxyGenerationOptions p = new ProxyGenerationOptions();
IPersistent ip = new Persistent();
p.AddMixinInstance(ip);
try
{
instance = this.ProxyGenerator.CreateClassProxy(implType, null, p, arguments, this.PersistenceInterceptor);
}
catch
{
throw new ComponentActivatorException("ComponentActivator: could not proxy " + implType.FullName, Model);
}
return instance;
}
}
我也尝试过像这样注册激活器,但无济于事......
Component.For<ProxyComponentActivator>()
.ImplementedBy<ProxyComponentActivator>()
.LifestyleSingleton()
在此先感谢您的帮助,路易斯