應用於裝飾上的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