我有一个ASP.NET Core 2.1应用程序,在几个.NET Standard 2.0项目的解决方案中引用。我想使用反射并使用实现的特定接口获取所有类型和过滤器,但它只返回通用接口,因此IsHandlerInterface
方法永远不会返回true。
List<AssemblyName> allAssemblies = Assembly.GetExecutingAssembly()
.GetReferencedAssemblies()
.Where(p => p.FullName.StartsWith("Something"))
.ToList(); // I get 4 assemblies here with the correct results
List<Type> allAssembliesTypes = allAssemblies
.Select(a => a.GetType())
.ToList(); // Retrieving the types
List<Type> handlerTypes = allAssembliesTypes
// typeof(ICommand).Assembly.GetTypes()
.Where(x => x.GetInterfaces().Any(y => IsHandlerInterface(y))) // Here I don't see the handler interface, only the generic ones, see method below
.Where(x => x.Name.EndsWith("Handler")) // Maybe redundant
.ToList();
private static bool IsHandlerInterface(Type type)
{
if (!type.IsGenericType)
return false;
Type typeDefinition = type.GetGenericTypeDefinition();
return typeDefinition == typeof(ICommandHandler<>) || typeDefinition == typeof(IQueryHandler<,>);
}
下面的处理程序示例。
public sealed class SampleCommandHandler : ICommandHandler<SampleCommand>
{
public SampleCommandHandler() // inject services
{
}
public Task<Result> HandleAsync(SampleCommand command)
{
// command logic
// preconditions handle
// trigger events
throw new NotImplementedException();
}
}
答案 0 :(得分:1)
此代码返回表示let str = " Name1, Name2, Name3 ";
let arr = str.replace(/\s+/g,'').split(',');
console.log(arr)
和ICommandHandler<>
的所有类型
IQueryHandler<>
答案 1 :(得分:0)
我能够使用下面的代码来获得所有带有引用的程序集。
List<Assembly> all = Assembly.GetEntryAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load);
答案 2 :(得分:0)
AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).Where(t => typeof(ResourceDictionary).IsAssignableFrom(t)).ToList();