Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic factory method for a generic interface

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).

like image 412
jgauffin Avatar asked Feb 19 '23 22:02

jgauffin


2 Answers

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.

like image 191
Steven Avatar answered Mar 04 '23 20:03

Steven


Do you really need TQuery in your factory? Could you not just use:

public void Register<TParameters, TResult>
        (Func<IQuery<TParameters, TResult>> factory)
    where TParameters : class
    where TResult : class
{
}

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

At that point, you've still got two type arguments, but assuming you'd usually want to fetch the query and immediately execute it, you could use type inference to allow something like:

public QueryExecutor<TResult> GetExecutor() where TResult : class
{
}

which would then have a generic method:

public IQueryable<TResult> Execute<TParameters>(TParameters parameters)
    where TParameters : class
{
}

So your original code would just become:

var query = _queryfactory.GetExecutor<UserResult>()
                         .Execute(new ActiveUsersParameters("a", "b"));

I don't know whether that will help in your actual case, but it's at least an option to consider.

like image 28
Jon Skeet Avatar answered Mar 04 '23 20:03

Jon Skeet