我正在使用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>();
它不再起作用了...... 这是一个错误,或者我做错了什么?
答案 0 :(得分:2)
这不是答案,但我无法将其纳入评论。这是一个最小的示例,显示它与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