Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查IoC注册是否实现命令或查询接口,并返回通用参数_C#_Generics_System.reflection_Simple Injector - Fatal编程技术网

C# 检查IoC注册是否实现命令或查询接口,并返回通用参数

C# 检查IoC注册是否实现命令或查询接口,并返回通用参数,c#,generics,system.reflection,simple-injector,C#,Generics,System.reflection,Simple Injector,我正在使用SimpleInjector IoC容器,并尝试在应用程序启动时连接功能(该容器将报告它已注册的命令处理程序和查询处理程序,我们将注册已注册为泛型类型的命令和查询): 我的接口和命令处理程序实现为: public interface ICommand { } class SetUserStatusToVerifiedCommand : ICommand { string UserId; DateTime VerifiedOn; } class SetUserStat

我正在使用SimpleInjector IoC容器,并尝试在应用程序启动时连接功能(该容器将报告它已注册的命令处理程序和查询处理程序,我们将注册已注册为泛型类型的命令和查询):

我的接口和命令处理程序实现为:

public interface ICommand
{
}

class SetUserStatusToVerifiedCommand : ICommand
{
    string UserId;
    DateTime VerifiedOn;
}

class SetUserStatusToVerifiedCommandHandler : ICommandHandler<SetUserStatusToVerifiedCommand>
{
    public void Handle(SetUserStatusToVerifiedCommand commandToHandle)
    {
    }
}
公共接口ICommand
{
}
类SetUserStatusToVerifiedCommand:ICommand
{
字符串用户标识;
日期时间验证;
}
类SetUserStatusToVerifiedCommandHandler:ICommandHandler
{
公共无效句柄(SetUserStatusToVerifiedCommand命令ToHandle)
{
}
}
你知道我做错了什么吗?


作为旁注,如果有任何更简单的方法可以通过SimpleInjector实现上述目标,我们将不胜感激。

问题在于此声明:

var type = registration.ServiceType;
var isCommandHandler = type.GetInterfaces().Any(x => x.IsGenericType 
    && x.GetGenericTypeDefinition() == typeof(ICommandHandler<>));

我可能会反过来做。由于您的命令标记为
ICommand
,因此获取所有命令应该像
AppDomain.CurrentDomain.GetAssemblies().GetTypes().Where(typeof(ICommand.IsAssignableFrom).Where(t=>!t.IsAbstract)
一样简单。谢谢@Steven我们可能会在不同的容器中托管不同的命令处理程序,因为可能有两个不同的系统(有界上下文)在同一进程中运行。。。我还没有充分考虑过这个想法,以实现范围界定的含义,但至少在最初,容器将是一个清晰的边界,因为我将为每个“系统”提供一个容器。在这种情况下,您所做的是有意义的。
public interface ICommand
{
}

class SetUserStatusToVerifiedCommand : ICommand
{
    string UserId;
    DateTime VerifiedOn;
}

class SetUserStatusToVerifiedCommandHandler : ICommandHandler<SetUserStatusToVerifiedCommand>
{
    public void Handle(SetUserStatusToVerifiedCommand commandToHandle)
    {
    }
}
var type = registration.ServiceType;
var isCommandHandler = type.GetInterfaces().Any(x => x.IsGenericType 
    && x.GetGenericTypeDefinition() == typeof(ICommandHandler<>));
var type = registration.ServiceType;

var isCommandHandler = type.IsGenericType && 
    type.GetGenericTypeDefinition() == typeof(ICommandHandler<>));