我想构建一个带有IInterceptionBehavior的缓存类,如此MSDN article中的describe,我想像属性一样使用它。
但是当我测试它时,我有这个错误:类型“CacheAction”没有可访问的构造函数。我需要你的帮助来理解原因。 “CacheAction”是我给构造函数的枚举。
这是代码,没有私有方法的缓存类:
/// <summary>
/// Cache action types.
/// </summary>
public enum CacheAction
{
/// <summary>
/// Add a new item to cache.
/// </summary>
Add,
/// <summary>
/// Remove all associated items from cache for the given domain model.
/// </summary>
Remove
}
[Serializable]
public class CacheAttribute : FilterAttribute, ICache, IInterceptionBehavior
{
private readonly ICache _cache;
[NonSerialized]
private object _syncRoot;
public readonly CacheAction _action;
public CacheAttribute(CacheAction action)
{
_cache = new StaticMemoryCache();
_action = action;
_syncRoot = new object();
}
public IMethodReturn Invoke(IMethodInvocation input,
GetNextInterceptionBehaviorDelegate getNext)
{
if (_action == CacheAction.Add)
{
var cacheKey = BuildCacheKey(input);
// If cache is empty, execute the target method, retrieve the return value and cache it.
if (_cache[cacheKey] == null)
{
lock (_syncRoot)
{
// Execute the target method
IMethodReturn returnVal = getNext()(input, getNext);
// Cache the return value
_cache[cacheKey] = returnVal;
return returnVal;
}
}
// Otherwise, return the cache result
return input.CreateMethodReturn(_cache[cacheKey]);
}
else
{
var typeName = GetTypeName(input.GetType());
lock (_syncRoot)
{
_cache.Remove(typeName);
}
IMethodReturn returnVal = getNext()(input, getNext);
return returnVal;
}
}
这里是Unity配置的代码(查看InterfaceInterceptor调用):
container.AddNewExtension<Interception>();
container
//.RegisterType<ICache, CacheAttribute>()
.RegisterType<IDataContextAsync, ApplicationDbContext>(new PerRequestLifetimeManager())
.RegisterType<IRepositoryProvider, RepositoryProvider>(
new PerRequestLifetimeManager(),
new InjectionConstructor(new object[] { new RepositoryFactories() })
)
.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerRequestLifetimeManager())
.RegisterType<IRepositoryAsync<Movie>, Repository<Movie>>(
new Interceptor<InterfaceInterceptor>(),
new InterceptionBehavior<CacheAttribute>())
.RegisterType<IMovieService, MovieService>()
.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerRequestLifetimeManager());
DependencyResolver.SetResolver(new Microsoft.Practices.Unity.Mvc.UnityDependencyResolver(container));
以下是我使用存储库进行测试的地方:
public static class MovieRepository
{
[Cache(CacheAction.Add)]
public static int test(this IRepositoryAsync<Movie> repository)
{
return 1;
}
}
所以,需要帮助才能理解我所缺少的错误:“CacheAction”类型没有可访问的构造函数。
谢谢,
大卫