如何从RequestFilter中访问ServiceStack的Service.Db实例?

时间:2015-02-03 19:53:09

标签: c# servicestack requestfiltering

我有一个C#ServiceStack RequestFilter ......

public class VerifyRequestedSystemsAttribute : Attribute, IHasRequestFilter
{
    IHasRequestFilter IHasRequestFilter.Copy()
    {
        return this;
    }


    public void RequestFilter(IRequest req, IResponse res, object requestDto)
    {
        var systemIds = RetrieveSystemIds(requestDto);

        Db.Select...? //How do I make Db available for use?
    }

    private List<int> RetrieveSystemIds(object requestDto)
    {
        // Find the properties on the requestDto having the RequestedSystemIds attribute
        var type = requestDto.GetType();
        var properties = type.GetPublicProperties();
        foreach (var systemIds in
                    from p in properties
                    where p.HasAttribute<RequestedSystemsAttribute>() && p.PropertyType == typeof(List<int>) && p.CanRead && p.CanWrite
                    select p.GetValue(requestDto, null)
                        as List<int>)
            return systemIds;

        return new List<int>();
    }


    // The lowest priority means it will run first, before other custom attributes
    public int Priority { get { return 0; } }
}

你能看到 - 在RequestFilter方法中我想查询数据库,但我无法访问Service.Db实例。

获取Service.Db实例的正确方法是什么?我应该使用ServiceRunner吗?

1 个答案:

答案 0 :(得分:2)

IOC依赖项也会在过滤器属性中注入,因此您可以添加请求过滤器属性所需的依赖项的公共属性,例如:

public class VerifyRequestedSystemsAttribute : Attribute, IHasRequestFilter
{
    public IDbConnectionFactory DbFactory { get; set; }

    private List<int> RetrieveSystemIds(object requestDto)
    {
        using (var db = DbFactory.OpenConnection())
        {
            //...
        }
    }
}