【问题标题】:How do I access ServiceStack's Service.Db instance from within a RequestFilter?如何从 RequestFilter 中访问 ServiceStack 的 Service.Db 实例?
【发布时间】:2015-04-03 03:47:32
【问题描述】:

我有一个 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 吗?

【问题讨论】:

    标签: c# servicestack requestfiltering


    【解决方案1】:

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

    public class VerifyRequestedSystemsAttribute : Attribute, IHasRequestFilter
    {
        public IDbConnectionFactory DbFactory { get; set; }
    
        private List<int> RetrieveSystemIds(object requestDto)
        {
            using (var db = DbFactory.OpenConnection())
            {
                //...
            }
        }
    }
    

    【讨论】:

    • 干杯神话,有没有什么地方可以阅读 ServiceStack 在框架的各个组件中注入的特定 IOC 依赖项?
    • @Drammy 它将任何已注册的 IOC 依赖项注入到您的类中,例如服务、过滤器和其他自动装配的部门。您还可以使用 HostContext.TryResolve&lt;IDep&gt;() 从任何地方解析 deps
    猜你喜欢
    • 1970-01-01
    • 2016-03-23
    • 2021-06-13
    • 2018-08-20
    • 2019-04-04
    • 2019-09-29
    • 2016-06-02
    • 1970-01-01
    • 2013-08-01
    相关资源
    最近更新 更多