动态代理仅适用于单身人士吗?

问题描述:

我正在使用Castle Dynamic ProxyStructureMap来实现日志拦截器,因此在我的依赖关系注册表中,我告诉StructureMap使用LoggingInterceptor装饰TrafficSourceRepository的所有实例。动态代理仅适用于单身人士吗?

var proxyGenerator = new ProxyGenerator(); 
For<ITrafficSourceRepository>(Lifecycles.Singleton) 
    .DecorateAllWith(instance => proxyGenerator 
    .CreateInterfaceProxyWithTargetInterface(instance, 
    new LoggingInterceptor(LogManager.GetLogger("AgencyPlayground")))) 
.Use<TrafficSourceRepository>(); 

enter image description here

一切似乎都很正常,它的工作原理,但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还是我做错了什么?

+0

通过不工作,你的意思是LoggingInterceptor不叫? – Evk

+0

是的,如果我将生命期改为瞬变,拦截器不拦截 – InferOn

+0

使用您发布的确切代码我无法复制它:生命周期瞬态拦截器仍然被调用。因此,也许你应该提供最小的工作示例来重现这一点。 – Evk

这不是一个答案,但我不能将其纳入评论。下面是一个小例子,表明它正常工作与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 
+0

我正在使用旧版本的StructureMap和StructureMap for MVC5,我将软件包更新到最新版本,现在它可以工作... – InferOn

+0

现在很高兴它现在得到解决 – Evk