dimanche 30 octobre 2016

How to automatically create wrapper for generic classes in autofac

I have simple code: public interface ICommand { }

public class CommandA : ICommand {}

public class CommandB :ICommand{}

public interface IHandler<in TCommand> where TCommand: ICommand { void Handle(TCommand command); }

public class Handler1: IHandler<CommandA> { public void Handle(CommandA command) {}}

public class Handler2: IHandler<CommandA> { public void Handle(CommandA c) {} }

public class Handler3: IHandler<CommandB> { public void Handle(CommandB c) {} }
public class Handler4: IHandler<CommandB> { public void Handle(CommandB c) {} }
}

I register all handlers using AsClosedTypesOf

builder.RegisterAssemblyTypes(myAssembly).AsClosedTypesOf(typeof(IHandler));

I have also dispacher class which should find all handler for given command and execute them

public class Dispatcher {
void Dispatch<TCommand>(TCommand command) where TCommand : ICommand {
    var handlers = context.Resolve<IEnumerable<IHandler<TCommand>>>();
    foreach (var handler in handlers) { handler.Handle(command); }}}

I have several problems here: 1) I want to have Dispatcher in different project and want to get rid of coupling to autofac

2) Really cannot find way to get/resolve all handlers from autofac. (I cannot register command because they can have other dependencies not known at registration)

3) I want to have another dispatcher which can user kind of wrapper on Handlers like this:

public class ActorHandler<TCommand> where TCommand : ICommand {
private IHandler<TCommand> _handler;

public ActorHandler(IHandler<TCommand> handler){
    _handler= handler;}
public void OnReceive(object obj) { var command = (TCommand)obj; _handler.Handle(command); }}

I'm not sure I can do it automatically for all handlers I have problem when I want to make kind of wrapper for every Handler

Aucun commentaire:

Enregistrer un commentaire