应用于装饰上的ASP.NET MVC 5应用程序,我有以下StructureMap配置:如何使用ASP.NET核心依赖注入
cfg.For(typeof(IRequestHandler<,>)).DecorateAllWith(typeof(MediatorPipeline<,>));
有谁知道如何做到这一点的配置与ASP.NET核心IOC ?
应用于装饰上的ASP.NET MVC 5应用程序,我有以下StructureMap配置:如何使用ASP.NET核心依赖注入
cfg.For(typeof(IRequestHandler<,>)).DecorateAllWith(typeof(MediatorPipeline<,>));
有谁知道如何做到这一点的配置与ASP.NET核心IOC ?
就我所知,开箱即用的IoC容器不支持装饰模式或自动发现,这是“按设计”。
这个想法是提供一个基本的IoC结构,它可以直接使用,也可以插入其他IoC容器来扩展默认功能。因此,如果您需要任何高级功能(支持特定的构造函数,自动注册实现接口或注入装饰器和拦截器的所有类型),您必须自己编写它或使用提供此功能的IoC容器。
此workaround不会将装饰器应用于某个类型的所有实例,而是使用扩展方法将装饰器逻辑抽象为另一个文件。
定义装饰结构,如:
public static class QueryHandlerRegistration
{
public static IServiceCollection RegisterQueryHandler<TQueryHandler, TQuery, TResult>(
this IServiceCollection services)
where TQuery : IQuery<TResult>
where TQueryHandler : class, IQueryHandler<TQuery, TResult>
{
services.AddTransient<TQueryHandler>();
services.AddTransient<IQueryHandler<TQuery, TResult>>(x =>
new LoggingDecorator<TQuery, TResult>(x.GetService<ILogger<TQuery>>(), x.GetService<TQueryHandler>()));
return services;
}
}
,把它想:
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.RegisterQueryHandler<FindThingByIdQueryHandler, FindThingByIdQuery, Thing>();
另外还有Scrutor包正在处理。
虽然此链接可能会回答问题,但最好在此处包含答案的基本部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/16875007) – rafalmp