You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 23:03:21