Skip to content

Instantly share code, notes, and snippets.

@mgroves
Created April 5, 2012 00:45
Show Gist options
  • Select an option

  • Save mgroves/2306949 to your computer and use it in GitHub Desktop.

Select an option

Save mgroves/2306949 to your computer and use it in GitHub Desktop.
ObjectFactory.Configure(x =>
{
var proxyGenerator = new ProxyGenerator();
x.For<IMyService>().Use<MyService>()
.EnrichWith(y => proxyGenerator.CreateInterfaceProxyWithTarget<IMyService>(y, new StaticCachingInterceptor()));
});
public interface IMyService
{
string GetSomeLongRunningResult(string input);
}
public class MyService : IMyService
{
public string GetSomeLongRunningResult(string input)
{
Thread.Sleep(5000); // simulate long running process
return string.Format("Result of '{0}' returned at {1}", input, DateTime.Now);
}
}
var myService = ObjectFactory.GetInstance<IMyService>();
Console.WriteLine("[{0}] Now getting the result with argument 'foo' for the first time...", DateTime.Now);
Console.WriteLine("[{0}] {1}", DateTime.Now, myService.GetSomeLongRunningResult("foo"));
Console.WriteLine("[{0}] Now getting the result with argument 'foo' for the second time...", DateTime.Now);
Console.WriteLine("[{0}] {1}", DateTime.Now, myService.GetSomeLongRunningResult("foo"));
Console.WriteLine("[{0}] Now getting the result with argument 'bar' for the first time...", DateTime.Now);
Console.WriteLine("[{0}] {1}", DateTime.Now, myService.GetSomeLongRunningResult("bar"));
// this is not a class you should actually use in production!
// this is just caching things in a static dictionary
// and individual items don't ever expire
// you should use a cache that suits your application, like ASP.NET's Cache class, AppFabric caching, etc.
public class StaticCachingInterceptor : IInterceptor
{
static readonly IDictionary<string, object> _cache;
static StaticCachingInterceptor()
{
_cache = new Dictionary<string, object>();
}
public void Intercept(IInvocation invocation)
{
var cacheKey = GenerateCacheKey(invocation.Method.Name, invocation.Arguments);
if (_cache.ContainsKey(cacheKey))
{
invocation.ReturnValue = _cache[cacheKey];
return;
}
invocation.Proceed();
_cache[cacheKey] = invocation.ReturnValue;
}
static string GenerateCacheKey(string name, object[] arguments)
{
if (arguments == null || arguments.Length == 0)
return name;
return name + "--" + string.Join("--", arguments.Select(a => a.ToString()).ToArray());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment