【问题标题】:Dynamic proxy generation only for singletons?仅针对单身人士的动态代理生成?
【发布时间】:2017-07-21 01:31:36
【问题描述】:

我正在使用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>();

一切似乎都很好,它可以工作,但是 TrafficSourceRepository 将被实例化为 Singleton,我不想这样做,所以我将已解析的 TrafficSourceRepositories 的生命周期更改为 Transient

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

它不再起作用了...... 这是一个错误还是我做错了什么?

【问题讨论】:

  • 不工作你的意思是 LoggingInterceptor 没有被调用?
  • 是的,如果我将生命周期更改为瞬态,拦截器不会拦截
  • 使用您发布的确切代码我无法重现它:仍然调用生命周期瞬态拦截器。所以也许你应该提供最小的工作示例来重现它。
  • @Evk 你能提供你的实现吗?

标签: c# structuremap castle-dynamicproxy


【解决方案1】:

这不是答案,但我无法将其纳入评论。这是一个最小的示例,表明它可以很好地与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

【讨论】:

  • 我使用的是旧版本的 StructureMap 和 StructureMap for MVC5,我将包更新到最新版本,现在它可以工作了...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-15
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
相关资源
最近更新 更多