Simpleinjector 위키의 지침에 따라 설정된 인터페이스, 명령 및 명령 처리기.
public interface ICommand
{
string Name { get; set; }
}
public class Command1 : ICommand
{
public string Name { get; set; }
}
public class Command2 : ICommand
{
public string Name { get; set; }
}
public interface ICommandHandler<TCommand>
{
void Execute(TCommand Command);
}
public class Command1Handler : ICommandHandler<Command1>
{
public void Execute(Command1 Command) {
Console.WriteLine(Command.Name);
}
}
public class Command2Handler : ICommandHandler<Command2>
{
public void Execute(Command2 Command) {
Console.WriteLine(Command.Name + "Hello");
}
}
데코레이터 :
public class CommandDecorator<TCommand> : ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> _handler;
public CommandDecorator(ICommandHandler<TCommand> handler)
{
this._handler = handler;
}
public void Execute(TCommand command)
{
this._handler.Execute(command);
}
}
샘플 프로그램
public class Program
{
static void Main(string[] args)
{
Container container = new Container();
//registering
container.RegisterAll<ICommand>(typeof(Command1), typeof(Command2));
container.RegisterManyForOpenGeneric(
typeof(ICommandHandler<>),
typeof(ICommandHandler<>).Assembly);
container.RegisterDecorator(typeof(ICommandHandler<>),
typeof(CommandDecorator<>));
container.Verify();
// sample test command
ICommand testcommand = new Command2();
testcommand.Name = "command 1";
var type = typeof(ICommandHandler<>).MakeGenericType(testcommand.GetType());
dynamic instance = container.GetInstance(type);
instance.Execute((dynamic)testcommand);
}
}
이것이 런타임에 명령을 처리하기위한 올바른 핸들러를 얻는 올바른 방법입니까? 이것은 샘플이며 실제 앱에서 명령은 대기열에 게시되고 서비스는 명령을 읽고 처리합니다. 나는 그것을 위해 Decorator를 사용해야한다고 생각하지만 그것을 작동시킬 수 없다. 더 나은 옵션이 있으면 제안하십시오.
명령 ( Command1
및 Command2
)은 서비스가 아닙니다. 등록해서는 안됩니다. 서비스 (명령 처리기)를 통해 전달하는 런타임 데이터 (메시지)입니다. 따라서 Collection.Register<ICommand>
( RegisterAll
v2에서) 등록을 제거해야합니다 . 소용이 없습니다. 귀하의 예제에서는 Command2
수동으로 새로 작성 하는 것이 옳은 일 이기 때문에 이미 쓸모 가 없습니다.
코드의 마지막 세 줄에서 수행중인 작업은 알 수없는 유형의 명령을 올바른 명령 처리기 등록에 전달하는 것입니다. ICommandHandler<TCommand>
컴파일 타임에 알지 못하는 명령 유형을 기반으로 닫힌 유형 을 빌드해야하기 때문에 항상이를 가져 오기 위해 약간의 반영이 필요합니다 . C # dynamic
키워드 를 사용하는 대신 .NET 리플렉션 API를 사용할 수도 있지만 내 경험상 dynamic
이 특정 경우에는 사용하는 것이 더 좋습니다. 리플렉션 API의 한 가지 중요한 단점은 API가 항상 throw 된 예외 (실패한 경우)를로 래핑 InvocationException
하므로 호출 스택을 처리하는 특정 예외를 수행하기가 더 어렵다는 것입니다.
짧게 말하면 다음과 같이 등록해야합니다.
Container container = new Container();
container.Register(
typeof(ICommandHandler<>),
typeof(ICommandHandler<>).Assembly);
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(CommandDecorator<>));
그리고 이것은 디스 패칭 로직이어야합니다.
var type = typeof(ICommandHandler<>).MakeGenericType(command.GetType());
dynamic handler = container.GetInstance(type);
handler.Execute((dynamic)command);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다