如何在DryIOC中实现与CastleWindsor等效的IInterceptor类型注册逻辑?
DryIOC 对应 CastleWindsor 拦截器注册的等效实现
以下CastleWindsor注册代码会扫描当前执行程序集中所有实现IInterceptor接口的类型,以单例生命周期注册到IOC容器,同时注册类型自身以及与类名匹配的默认接口(比如类名AuditingStore会对应注册IAuditingStore接口):
IocContainer.Register( Classes.FromAssembly(Assembly.GetExecutingAssembly()) .IncludeNonPublicTypes() .BasedOn<IInterceptor>() .WithService.Self() .WithService.DefaultInterfaces() .LifestyleSingleton() );
举个例子,对于如下实现IAuditingStore和IInterceptor的类,上述代码会将其注册为IAuditingStore服务:
public class AuditingStore : IAuditingStore, IInterceptor {}
在DryIOC中,可通过以下代码实现完全等效的功能:
using DryIoc; using System.Reflection; var container = new Container(); container.RegisterMany( assemblies: new[] { Assembly.GetExecutingAssembly() }, serviceTypeCondition: type => type.IsAssignableTo(typeof(IInterceptor)), setup: Setup.With(includeNonPublicTypes: true, lifestyle: Lifestyle.Singleton), serviceSelector: (type, _) => new[] { type } .Concat(type.GetInterfaces() .Where(i => i.Name.Equals($"I{type.Name}", StringComparison.Ordinal))) );
代码说明
RegisterMany是DryIOC的批量注册方法,用于处理程序集扫描场景assemblies指定扫描范围为当前执行程序集serviceTypeCondition筛选出所有实现IInterceptor的类型setup启用非公开类型扫描,并设置单例生命周期serviceSelector自定义服务注册逻辑:同时注册类型自身,以及名称符合I{类名}格式的接口,对应CastleWindsor中的WithService.Self()和WithService.DefaultInterfaces()
内容的提问来源于stack exchange,提问作者reach4thelasers
相关产品推荐
相关产品推荐

