Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8670893
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T18:48:52+00:00 2026-06-12T18:48:52+00:00

I want to be able to specify a typed interface which can be used

  • 0

I want to be able to specify a typed interface which can be used with queries. I ultimately want to be able to do something like:

var query = _queryfactory.Create<IActiveUsersQuery>();
var result = query.Execute(new ActiveUsersParameters("a", "b"));
foreach (var user in result)
{
    Console.WriteLine(user.FirstName);
}

Looks simple enough, ehh? Notice that the query got typed parameters and a typed result. To be able to restrict the query factory to only contain queries we’ll have to specify something like:

public interface IQuery<in TParameters, out TResult>
    where TResult : class
    where TParameters : class
{
    TResult Invoke(TParameters parameters);
}

But that’s going to spread like cancer:

// this was easy
public interface IActiveUsersQuery : IQuery<ActiveUsersParameters, UserResult>
{

}

//but the factory got to have those restrictions too:
public class QueryFactory
{
    public void Register<TQuery, TParameters, TResult>(Func<TQuery> factory)
        where TQuery : IQuery<TParameters, TResult>
        where TParameters : class
        where TResult : class
    {
    }

    public TQuery Create<TQuery, TParameters, TResult>()
        where TQuery : IQuery<TParameters, TResult>
        where TParameters : class
        where TResult : class
    {
    }
}

Which ultimately leads to a factory invocation like:

factory.Create<IActiveUsersQuery, ActiveUsersParameters, UserResult>();

Not very nice since the user have to specify the parameter type and the result type.

Am I trying to control it too much? Should I just create a dummy interface:

public interface IQuery
{

}

to show the intent and then let the users create whatever they like (since they, and not the factory, will invoke the correct query).

However, the last option isn’t very nice since it won’t let me decorate queries (for instance dynamically cache them by using a caching decorator).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T18:48:52+00:00Added an answer on June 12, 2026 at 6:48 pm

    I completely understand what you are trying to do here. You are applying the SOLID principles, so query implementations are abstracted away from the consumer, who merely sends a message (DTO) and gets a result. By implementing a generic interface for the query, we can wrap implementations with a decorator, which allows all sorts of interesting behavior, such as transactional behavior, auditing, performance monitoring, caching, etc, etc.

    The way to do this is to define the following interface for a messsage (the query definition):

    public interface IQuery<TResult> { }
    

    And define the following interface for the implemenation:

    public interface IQueryHandler<TQuery, TResult>
        where TQuery : IQuery<TResult>
    {
        TResult Handle(TQuery query);
    }
    

    The IQuery<TResult> is some sort of marker interface, but this allows us to define statically what a query returns, for instance:

    public class FindUsersBySearchTextQuery : IQuery<User[]>
    {
        public string SearchText { get; set; }
    
        public bool IncludeInactiveUsers { get; set; }
    }
    

    An implementation can be defined as follows:

    public class FindUsersBySearchTextQueryHandler
        : IQueryHandler<FindUsersBySearchTextQuery, User[]>
    {
        private readonly IUnitOfWork db;
    
        public FindUsersBySearchTextQueryHandler(IUnitOfWork db)
        {
            this.db = db;
        }
    
        public User[] Handle(FindUsersBySearchTextQuery query)
        {
            // example
            return (
                from user in this.db.Users
                where user.Name.Contains(query.SearchText)
                where user.IsActive || query.IncludeInactiveUsers
                select user)
                .ToArray();
        }
    }
    

    Consumers can no take a dependency on the IQueryHandler<TQuery, TResult> to execute queries:

    public class UserController : Controller
    {
        IQueryHandler<FindUsersBySearchTextQuery, User[]> handler;
    
        public UserController(
            IQueryHandler<FindUsersBySearchTextQuery, User[]> handler)
        {
            this. handler = handler;
        }
    
        public View SearchUsers(string searchString)
        {
            var query = new FindUsersBySearchTextQuery
            {
                SearchText = searchString,
                IncludeInactiveUsers = false
            };
    
            User[] users = this.handler.Handle(query);
    
            return this.View(users);
        }
    }
    

    This allows you to add cross-cutting concerns to query handlers, without consumers to know this and this gives you complete compile time support.

    The biggest downside of this approach (IMO) however, is that you’ll easily end up with big constructors, since you’ll often need to execute multiple queries, (without really violating the SRP).

    To solve this, you can introduce an abstraction between the consumers and the IQueryHandler<TQuery, TResult> interface:

    public interface IQueryProcessor
    {
        TResult Execute<TResult>(IQuery<TResult> query);
    }
    

    Instread of injecting multiple IQueryHandler<TQuery, TResult> implementations, you can inject one IQueryProcessor. Now the consumer will look like this:

    public class UserController : Controller
    {
        private IQueryProcessor queryProcessor;
    
        public UserController(IQueryProcessor queryProcessor)
        {
            this.queryProcessor = queryProcessor;
        }
    
        public View SearchUsers(string searchString)
        {
            var query = new FindUsersBySearchTextQuery
            {
                SearchText = searchString
            };
    
            // Note how we omit the generic type argument,
            // but still have type safety.
            User[] users = this.queryProcessor.Execute(query);
    
            return this.View(users);
        }
    }
    

    The IQueryProcessor implementation can look like this:

    sealed class QueryProcessor : IQueryProcessor
    {
        private readonly Container container;
    
        public QueryProcessor(Container container)
        {
            this.container = container;
        }
    
        [DebuggerStepThrough]
        public TResult Execute<TResult>(IQuery<TResult> query)
        {
            var handlerType = typeof(IQueryHandler<,>)
                .MakeGenericType(query.GetType(), typeof(TResult));
    
            dynamic handler = container.GetInstance(handlerType);
    
            return handler.Handle((dynamic)query);
        }
    }
    

    It depends on the container (it is part of the composition root) and uses dynamic typing (C# 4.0) to execute the queries.

    This IQueryProcessor is effectively your QueryFactory.

    There are downsides of using this IQueryProcessor abstraction though. For instance, you miss the possibility to let your DI container verify whether a requested IQueryHandler<TQuery, TResult> implementation exists. You’ll find out at the moment that you call processor.Execute instead when requesting a root object. You can solve this by writing an extra integration test that checks if an IQueryHandler<TQuery, TResult> is registered for each class that implements IQuery<TResult>. Another downside is that the dependencies are less clear (the IQueryProcessor is some sort of ambient context) and this makes unit testing a bit harder. For instance, your unit tests will still compile when a consumer runs a new type of query.

    You can find more information about this design in this blog post: Meanwhile… on the query side of my architecture.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to be able to do something like this <test:TabControl id= runat=server....> <ItemTemplate>
Why I can't able to specify static type of methods in interface. Is there
How can I specify that I want any object that implements the A interface
Basically I want to be able to specify an xml or 2 like so
I have a situation where I want users to be able to specify a
Want to be able to provide a search interface for a collection of objects
I want to be able to specify the properties to get populated/updated in the
I have a view function which renders json. I am able to specify which
I'm implementing a REST-style interface and would like to be able to create (via
Learning more about code contracts, they seem like something I want to use in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.