动态代理仅适用于单身人士吗?
问题描述:
我正在使用Castle Dynamic Proxy和StructureMap来实现日志拦截器,因此在我的依赖关系注册表中,我告诉StructureMap使用LoggingInterceptor装饰TrafficSourceRepository的所有实例。动态代理仅适用于单身人士吗?
var proxyGenerator = new ProxyGenerator();
For<ITrafficSourceRepository>(Lifecycles.Singleton)
.DecorateAllWith(instance => proxyGenerator
.CreateInterfaceProxyWithTargetInterface(instance,
new LoggingInterceptor(LogManager.GetLogger("AgencyPlayground"))))
.Use<TrafficSourceRepository>();
一切似乎都很正常,它的工作原理,但TrafficSourceRepository将被实例化作为Singleton
,我不想,所以我改变解决TrafficSourceRepositories的寿命为Transient
:
var proxyGenerator = new ProxyGenerator();
For<ITrafficSourceRepository>(Lifecycles.Transient)
.DecorateAllWith(instance => proxyGenerator
.CreateInterfaceProxyWithTargetInterface(instance,
new LoggingInterceptor(LogManager.GetLogger("AgencyPlayground"))))
.Use<TrafficSourceRepository>();
,它不工作了...... 这是bug还是我做错了什么?
答
这不是一个答案,但我不能将其纳入评论。下面是一个小例子,表明它正常工作与Lifecycles.Transient
:
class Program {
public static void Main() {
var proxyGenerator = new ProxyGenerator();
var container = new Container(config => {
config.For<ITrafficSourceRepository>(Lifecycles.Transient)
.DecorateAllWith(instance => proxyGenerator
.CreateInterfaceProxyWithTargetInterface(instance,
new LoggingInterceptor()))
.Use<TrafficSourceRepository>();
});
var ts = container.GetInstance<ITrafficSourceRepository>();
ts.Call();
Console.ReadKey();
}
}
public interface ITrafficSourceRepository {
void Call();
}
public class TrafficSourceRepository : ITrafficSourceRepository {
public void Call() {
Console.WriteLine("Called");
throw new Exception("Ex");
}
}
public class LoggingInterceptor : IInterceptor {
public void Intercept(IInvocation invocation) {
try {
invocation.Proceed();
}
catch (Exception ex) {
Console.WriteLine("Intercepted: " + ex.Message);
}
}
}
输出:
Called
Intercepted: Ex
通过不工作,你的意思是LoggingInterceptor不叫? – Evk
是的,如果我将生命期改为瞬变,拦截器不拦截 – InferOn
使用您发布的确切代码我无法复制它:生命周期瞬态拦截器仍然被调用。因此,也许你应该提供最小的工作示例来重现这一点。 – Evk