问题描述
我有一个需要某种状态才能运行的 MixIn.
I have a MixIn that requires some state to operate.
我是这样注册的..
container.Register(Component.For(Of ICat) _
.ImplementedBy(Of Cat) _
.LifeStyle.Transient _
.Proxy.MixIns(New MyMixin()))
当我调用 container.Resolve(of ICat) 时,我得到了 ICat 的代理,它也实现了 IMixin.
When I call container.Resolve(of ICat), I get back a proxy for ICat, which also implements IMixin.
但是,如果我再次调用 container.Resolve(of ICat),我将获得 ICat 的新代理,但 MyMixin 是相同的实例.(这是有道理的,因为我没有告诉容器以任何方式创建 IMixin)
However, if I call container.Resolve(of ICat) again, I get a new proxy for ICat, but MyMixin is the SAME instance. (Which makes sense because I didn't tell the container any way to create IMixin)
所以,IMixin 是一个单例,即使组件的生活方式是瞬态的.
So, IMixin is a Singleton, even though the Component's lifestyle is Transient.
如何通过 Fluent Interface 告诉 Windsor 为组件创建新的 MyMixIn 实例?
How can I tell Windsor, though the Fluent Interface, to create a new Instance of MyMixIn for the component?
推荐答案
我想我已经解决了这个问题.
I think I resolved this.
我没有使用 Proxy.Mixins,而是创建了一个自定义的 Activator()
Instead of using Proxy.Mixins, I created a custom Activator()
Public Class MixInActivator(Of T)
Inherits Castle.MicroKernel.ComponentActivator.DefaultComponentActivator
Public Sub New(ByVal model As Castle.Core.ComponentModel, ByVal kernel As Castle.MicroKernel.IKernel, ByVal OnCreation As Castle.MicroKernel.ComponentInstanceDelegate, ByVal OnDestruction As Castle.MicroKernel.ComponentInstanceDelegate)
MyBase.New(model, kernel, OnCreation, OnDestruction)
End Sub
Protected Overrides Function InternalCreate(ByVal context As Castle.MicroKernel.CreationContext) As Object
Dim obj As Object = MyBase.InternalCreate(context)
If GetType(T).IsAssignableFrom(obj.GetType) = False Then
Dim options As New Castle.DynamicProxy.ProxyGenerationOptions
Dim gen As New Castle.DynamicProxy.ProxyGenerator
options.AddMixinInstance(Kernel.Resolve(Of T))
obj = gen.CreateInterfaceProxyWithTarget(Model.Service, obj, options)
End If
Return obj
End Function
End Class
那么现在组件就这样注册了
So now, the component is registered like this
container.Register(Component.For(Of ICat) _
.ImplementedBy(Of Cat) _
.LifeStyle.Is(Castle.Core.LifestyleType.Transient) _
.Activator(Of MixInActivator(Of IMixin)))
和IMixin注册如下
And IMixin is registered as follows
container.Register(Component.For(Of IMixin) _
.ImplementedBy(Of MyMixin) _
.LifeStyle.Is(Castle.Core.LifestyleType.Transient) _
.Named("MyMixin"))
这篇关于温莎 MixIn 是单身人士吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!