Assembly scanning with attribute and named service in .NET Core

302 Views Asked by At

I've been asked to create a .NET Core implementation of CQRS pattern with the peculiarity that the request and response need to be generic because are generated client side.

Limiting the example to queries, any query had an handle method like this:

public async Task<QueryResponseDTO> Handle (QueryRequestDTO request)

Where DTOs have a property inside that indicate the QueryName and are received using a broker (KubeMQ by the way).

Given the fact that DTOs are always the same, I cannot use Mediatr to dispatch the queries, so I'm trying to create a mechanism using named service registration to make this work.

My idea is to create an attribute to be added to our queries classes and use that to populate a named service at startup.

I've created this attribute:

public class AutoWireQueryNameAttribute : Attribute
{
    public string QueryName { get; private set; }

    public AutoWireQueryNameAttribute(string queryName) 
    {
        QueryName = queryName;
    }
}

And class is tagged like this:

[AutoWireQueryName("GET_ALL_USERS")]
public class GetAllUsersQueryHandler : IRequestHandler<QueryRequestDTO, QueryResponseDTO>
{
    public async Task<QueryResponseDTO> Handle(QueryRequestDTO request)
    {
    }
}

And then, at runtime, using something like this to resolve the correct handler:

var instance = container.GetInstance<IRequestHandler>("GET_ALL_USERS");

My problem arise when I need to wire up everything inside the startup.cs with something like this:

services
    .Scan(scan => scan
        .FromApplicationDependencies()
        .AddClasses(f => f.WithAttribute<AutoWireQueryNameAttribute>())
        .UsingRegistrationStrategy(RegistrationStrategy.Append)
        .AsSelfWithInterfaces())

I've come to understand that probably I will need an external IoC container to make this work (as scrutor is not the correct tool), but reading on Lighinject and Autofac documentation I couldn't find any useful indication on how to handle the service registration .

Any advice? I've taken a wrong road?

0

There are 0 best solutions below