TylerBrinks/Snap — Issue #19: Snap generating fresh dynamic assemblies each invocation
Author: coatesjable
Created: 2011-10-18 12:51:08+00:00
State: open

Hello there,

I use SNAP + StructureMap to provide AOP support for my OpenRasta (OR) IIS Hosted application. My OR Handlers have attributes applied to them, lets say:

```csharp
[Log("service")]
public OperationResult Get()
```

Where log is define as:

```csharp
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class LogAttribute : MethodInterceptAttribute
{
//blarg
}
```

```csharp
public class LogInterceptor : MethodInterceptor
{
public override void InterceptMethod(IInvocation invocation, MethodBase method, Attribute attribute)
{
//zub zub
}
}
```

My OR Handlers are wired up through my IoC registry.

My snap configuration looks something like this:

```csharp
SnapConfiguration
.For(c =>
{
c.IncludeNamespace("services*");
c.Bind()
.To().Order(0);
c.Bind().To
().Order(1);
c.AllAspects().KeepInContainer();
});
```

Hopefully that is enough primer info.

Every time my handler is invoked a few dynamic assemblies are created:

"DynamicProxyGenAssembly2"

These assemblies are loaded (around 4 of them but i dont think thats entirely relevant) and are never unloaded. This means that after a certain number of requests the unmanaged memory usage of my application gets really high and we have to recycle the app pool in order to prevent OutOfMemory exceptions.

Having looked through the SNAP / SNAP.StructureMap codebase I've tracked the piece of code that makes the dynamic assemblies and loads them into the app domain:

```csharp
public static object CreateProxy(Type interfaceType, object instanceToWrap, params IInterceptor[] interceptors)
{
if (interfaceType.IsInterface)
return new ProxyGenerator().CreateInterfaceProxyWithTargetInterface(interfaceType, instanceToWrap, interceptors.ToArray());
//rest doesnt get executed
}
```

After the call to proxy generator is make I have an addtional two dynamic assemblies loaded into the app domain.

I would have though that this sort of information would have been cached somehow. Is there a mechanism I've missed in Snap or in Castle.Proxy that will prevent this information from being continually generated?

Any help would be greatly appreciated,

J