0

I'm looking at using ServiceStack's AutoQuery feature and I have some basic queries working. However I'd like to implement a global filter since I have a multi-tenanted database, e.g.,

All queries should be appended with the criteria CustomerId = Session.CustomerId

What would be the best way to do this?

vonec
  • 681
  • 10
  • 22

1 Answers1

2

You could potentially use a custom AutoQuery base class for this to append the custom filter to each query, e.g:

public abstract class MyAutoQueryServiceBase : AutoQueryServiceBase
{
    public override object Exec<From>(IQuery<From> dto)
    {
        var q = AutoQuery.CreateQuery(dto, Request);
        var session = base.SessionAs<CustomUserSession>();
        q.And("CustomerId = {0}", session.CustomerId);

        return AutoQuery.Execute(dto, q);
    }

    public override object Exec<From, Into>(IQuery<From, Into> dto)
    {
        var q = AutoQuery.CreateQuery(dto, Request);
        var session = base.SessionAs<CustomUserSession>();
        q.And("CustomerId = {0}", session.CustomerId);

        return AutoQuery.Execute(dto, q);
    }
}

Then tell AutoQuery to use your base class instead, e.g:

Plugins.Add(new AutoQueryFeature { 
    AutoQueryServiceBaseType = typeof(MyAutoQueryServiceBase)
});
mythz
  • 141,670
  • 29
  • 246
  • 390
  • The MyAutoQueryServiceBase example will work, however it'll not provide compile time safety. What if I want a different signature where I want to enforce the type From is of some particular interface, e.g. interface IMustHaveSomeCustomerId? something like public object Exec(IQuery dto) where From : IMustHaveSomeCustomerId – Jeff Apr 18 '16 at 06:14
  • is there a way to only use AutoQuery.CreateQuery to generate a sql expression but have the AutoQueryServiceBase disabled? So that I must provided implementation for all IQuery manually? This may sound strange, but without the ability to provide compile time type safety, I can't just blindingly, do a q.And("CustomerId = {}) as suggested in the answer. – Jeff Apr 18 '16 at 06:17
  • 1
    @Jeff if you want a Typed API with ability to use an Interface have a look at [Query Filters](https://github.com/ServiceStack/ServiceStack/wiki/Auto-Query#extensibility-with-queryfilters) – mythz Apr 18 '16 at 07:06
  • is it a bug or am I doing something wrong, that when doing .RegisterQueryFilter((req, q, dto) =>, the req is NULL. I'm using SS 4.0.50. – Jeff Apr 19 '16 at 00:05
  • @Jeff Can't tell please open a new question with all the code you're using. – mythz Apr 19 '16 at 00:10
  • @Jeff eventually, there's still a lot of hours left in the US :) – mythz Apr 19 '16 at 00:54