6

我正在遵循steven记录的一些实践并使用Simple Injector。我有一个从 WCF 服务检索数据的查询,我想使用.ObjectCache

我定义了一个装饰器CachingQueryHandlerDecorator<TQuery, TResult>

public sealed class CachingQueryHandlerDecorator<TQuery, TResult>
    : IQueryHandler<TQuery, TResult>
    where TQuery : IQuery<TResult>
{
    private readonly IQueryHandler<TQuery, TResult> _handler;
    private readonly ObjectCache _cache;
    private readonly CacheItemPolicy  _policy;
    private readonly ILog _log;

    public CachingQueryHandlerDecorator(IQueryHandler<TQuery, TResult> handler,
                                        ObjectCache cache,
                                        CacheItemPolicy policy,
                                        ILog log)
    {
        _handler = handler;
        _cache = cache;
        _policy = policy;
        _log = log;
    }

    public TResult Handle(TQuery query)
    {
        var key = query.GetType().ToString();
        var result = (TResult) _cache[key];
        if (result == null)
        {
            _log.Debug(m => m("No cache entry for {0}", key));
            result = (TResult)_handler.Handle(query);
            if (!_cache.Contains(key))
                _cache.Add(key, result, _policy);
        }
        return result;
    }
}

SimpleInjectorInitializer.cs我定义缓存和策略,并为特定查询添加装饰器:

container.RegisterSingle<ILog>(LogManager.GetCurrentClassLogger());
container.RegisterSingle<ObjectCache>(() => new MemoryCache("MyCache"));
container.RegisterSingle<CacheItemPolicy>(() => new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(1) } );
.
.
.
container.RegisterDecorator(typeof(IQueryHandler<,>),
    typeof(CachingQueryHandlerDecorator<,>),
    ctx => ctx.ServiceType.GetGenericArguments()[0] == typeof(MyQuery));

我面临的问题是我希望能够CacheItemPolicy为不同的查询指定不同的 's。我可以创建一个新ICachePolicy<TQuery>接口,然后为每种不同的查询类型定义具体的类,但我希望有一种方法可以避免这种情况,并直接在初始化文件中定义每个查询的策略。

4

2 回答 2

14

我可以创建一个新的 ICachePolicy 接口,然后为每个不同的查询类型定义具体的类

我认为这实际上是一个非常巧妙的想法。您可以注册一个默认的通用实现,该实现注入到每个没有注册特定实现的装饰器中:

container.RegisterOpenGeneric(typeof(ICachePolicy<>), typeof(DefaultCachePolicy<>),
    Lifestyle.Singleton);

对于具有备用缓存策略的查询,您可以注册特定的实现:

container.RegisterSingle<ICachePolicy<MyQuery>>(new CachePolicy<MyQuery> 
{
    AbsoluteExpiration = DateTime.Now.AddHour(2)
});

另一种选择是使用描述缓存策略的属性标记查询或其查询处理程序(这是我通常采用的路线):

[CachePolicy(AbsoluteExpirationInSeconds = 1 * 60 * 60)]
public class MyQuery : IQuery<string[]> { }

现在您不必注入ICachePolicy<T>,但可以使用反射直接读取此元数据:

public sealed class CachingQueryHandlerDecorator<TQuery, TResult>
    : IQueryHandler<TQuery, TResult>
    where TQuery : IQuery<TResult>
{
    private static readonly bool shouldCache;
    private static readonly CachingPolicySettings policy;

    private readonly IQueryHandler<TQuery, TResult> _handler;
    private readonly ObjectCache _cache;
    private readonly ILog _log;

    static CachingQueryHandlerDecorator()
    {
        var attribute = typeof(TQuery).GetCustomAttribute<CachePolicyAttribute>();

        if (attribute != null)
        {
            shouldCache = true;
            policy = attribute.Policy;
        }
    }

    public CachingQueryHandlerDecorator(
        IQueryHandler<TQuery, TResult> handler,
        ObjectCache cache,
        ILog log)
    {
        _handler = handler;
        _cache = cache;
        _log = log;
    }

    public TResult Handle(TQuery query)
    {
        if (!shouldCache)
        {
            return this._handler.handle(query);
        }

        // do your caching stuff here.
    }
于 2013-11-06T09:37:13.557 回答
7

您可以通过开放的通用实现实现所需的结果,并根据需要覆盖特定的默认值。即,您定义了一个开放的通用实现CachePolicy<TQuery>ICachePolicy<TQuery>使用该RegisterInitializer方法覆盖默认实现的部分内容。

鉴于这些定义:

public interface ICachePolicy<TQuery>
{
    DateTime AbsoluteExpiration { get; }
}

public class CachePolicy<TQuery> : ICachePolicy<TQuery>
{
    public CachePolicy()
    {
        AbsoluteExpiration = Cache.NoAbsoluteExpiration;
    }

    public DateTime AbsoluteExpiration { get; set; }
}

public interface IQueryHandler<TQuery, TResult> { }
public class QueryHandlerA : IQueryHandler<A, AResult> { }
public class QueryHandlerB : IQueryHandler<B, BResult> { }

public sealed class CachingQueryHandlerDecorator<TQuery, TResult>
    : IQueryHandler<TQuery, TResult>
{
    private readonly IQueryHandler<TQuery, TResult> decorated;
    public readonly ICachePolicy<TQuery> Policy;

    public CachingQueryHandlerDecorator(
        IQueryHandler<TQuery, TResult> decorated,
        ICachePolicy<TQuery> cachePolicy)
    {
        this.decorated = decorated;
        this.Policy = cachePolicy;
    }
}

使用该方法设置容器并使用以下RegisterOpenGeneric方法配置非默认值RegisterInitializer

public Container ConfigureContainer()
{
    Container container = new Container();

    container.RegisterOpenGeneric(
        typeof(ICachePolicy<>), 
        typeof(CachePolicy<>), 
        Lifestyle.Singleton);

    container.RegisterInitializer<CachePolicy<A>>(a =>
        a.AbsoluteExpiration = DateTime.Now.AddMinutes(1));

    container.RegisterManyForOpenGeneric(
        typeof(IQueryHandler<,>),
        typeof(IQueryHandler<,>).Assembly);

    container.RegisterDecorator(
        typeof(IQueryHandler<,>), 
        typeof(CachingQueryHandlerDecorator<,>));

    container.Verify();

    return container;
}

这些测试表明结果符合预期:

[Test]
public void GetInstance_A_HasCustomAbsoluteExpiration()
{
    Container container = ConfigureContainer();

    var a = container.GetInstance<IQueryHandler<A, AResult>>();

    Assert.AreNotEqual(
        (a as CachingQueryHandlerDecorator<A, AResult>).Policy.AbsoluteExpiration,
        Cache.NoAbsoluteExpiration);
}

[Test]
public void GetInstance_B_HasDefaultAbsoluteExpiration()
{
    Container container = ConfigureContainer();

    var b = container.GetInstance<IQueryHandler<B, BResult>>();

    Assert.AreEqual(
        (b as CachingQueryHandlerDecorator<B, BResult>).Policy.AbsoluteExpiration,
        Cache.NoAbsoluteExpiration);
}
于 2013-11-06T09:37:19.690 回答