I have the following in QUERY side of Project1 which primarily contains interfaces
public interface IQueryResult {}
public interface IQuery<TResult> where TResult : IQueryResult {}
public interface IQueryHandler<TQuery, TResult>
where TQuery : IQuery<TResult>
where TResult : IQueryResult
{
Task<TResult> HandleAsync(TQuery query);
}
public class PersonQueryResult : IQueryResult
{
public string Name { get; set; }
}
public class GetPersonDetailsQuery : IQuery<PersonQueryResult>
{
public int Id { get; set; }
}
public interface IQueryDispatcher
{
Task<TResult> DispatchAsync<TQuery, TResult>(TQuery query)
where TQuery : IQuery<TResult>
where TResult : IQueryResult;
}
In the Second Project2 which references Project 1, I have
public class GetPersonDetailsQueryHandler :
IQueryHandler<GetPersonDetailsQuery, PersonQueryResult>
{
public Task<PersonQueryResult> HandleAsync(GetPersonDetailsQuery query)
{
return Task.FromResult( new PersonQueryResult {Name = "Bamboo"});
}
}
The last Project 3 is a Web API project which only references Project 1 but NOT project 2. So it knows the interfaces and the commands and queries only. I need to configure autofac in a way that i can easily do something like this
var query = new GetPersonDetailsQuery { Id = 1 };
var magicHappensHere = new QueryDispatcher(); //any better way?
PersonQueryResult result = magicHappensHere.Dispatch(query);
Also the IQueryDispatcher
I have in Project 1 does not seem fit for the job above.
A sample implementation for that interface which is open for suggestions is
public class QueryDispatcher : IQueryDispatcher
{
private readonly IComponentContext _context;
public QueryDispatcher(IComponentContext context)
{
this._context = context;
}
public Task<TResult> DispatchAsync<TQuery, TResult>(TQuery query) where TQuery : IQuery<TResult> where TResult : IQueryResult
{
var handler = _context.Resolve<IQueryHandler<TQuery, TResult>>();
return handler.HandleAsync(query);
}
}
Possible solutions that I dont know how to implement (A) Define an Autofac module in Project 2 and then Scan the Project 2 assembly in Web API?.. (B) http://docs.autofac.org/en/latest/register/registration.html#open-generic-components (C) Scanning assembly and trying to map automatically. Need help with code to be inserted here
private static void ConfigureAutofac(HttpConfiguration config)
{
var builder = new ContainerBuilder();
//*************//
//what to do here?
//**************//
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterWebApiFilterProvider(config);
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}