我有带有StructureMap和Mediatr的ASP.NET Core 3.1。
以前,当我使用默认的DI容器时,我的子处理程序将触发两次。那里的功能非常有限,所以我切换到StructureMap。但是,当我对扫描仪应用不同的设置时,却无法获得预期的行为。它是执行两次的基本处理程序或子处理程序,或两者都执行。唯一可行的情况是,我没有为typeof(INotificationHandler<>)
指定任何内容,由于Auto Wiring(可能是?),一切正常,但是我感觉通知处理程序调用之间存在延迟,所以我d想在应用程序启动时正确配置容器。
我的通知和通知处理程序如下。 预期行为:发布子通知时,一次触发两个处理程序
public class ApplicationUserRegisteredNotification : INotification
{
public ApplicationUser User { get; }
public ApplicationUserRegisteredNotification(ApplicationUser user)
{
User = user;
}
}
public class SpecificUserRegisteredNotification : ApplicationUserRegisteredNotification
{
public SpecificUserProfile SpecificUser { get; }
public SpecificUserRegisteredNotification(SpecificUserProfile specificUser)
: base(specificUser.User)
{
SpecificUser = specificUser;
}
}
public class SendEmailConfirmationEmail : INotificationHandler<ApplicationUserRegisteredNotification>
{
// some code
}
public class SendAdminVerifySpecificUserRegistration : INotificationHandler<SpecificUserRegisteredNotification>
{
// some code
}
我使用StructureMap.AspNetCore
来产生IServiceProvider
,我可以使用什么选项来明确地应用自动装配逻辑?在下面的注释中,您可以看到每个选项的输出。
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// some code
var container = new Container(cfg =>
{
cfg.Scan(scanner =>
{
scanner.AssemblyContainingType(GetType());
scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<>));
scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>));
//scanner.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>)); // both handlers triggered twice in given sequence: base,child,base,child
//scanner.AddAllTypesOf(typeof(INotificationHandler<>)); // both handlers triggered in given sequence: base,child
// nothing: everything works as expected - base,but switching between handlers is rather slow
});
});
container.Populate(services);
return container.GetInstance<IServiceProvider>();
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStructureMap()
.UseStartup<Startup>();
}
在StructureMap之前,我的配置是这样的
services.AddTransient<INotificationHandler<SpecificUserRegisteredNotification>,SendEmailConfirmationEmail>();
services.AddTransient<INotificationHandler<OtherSpecificUserRegisteredNotification>,SendEmailConfirmationEmail>();
services.AddTransient<IRequestHandler<RegisterSpecificCommand,BaseCommandResponse>,RegisterApplicationUserCommandHandler>();
services.AddTransient<IRequestHandler<RegisterOtherSpecificCommand,RegisterApplicationUserCommandHandler>();