【问题标题】:Autofac, how to intercept the service with an instance of a Aspect but not with the Type of Aspect?Autofac,如何使用 Aspect 的实例而不是 Aspect 的类型来拦截服务?
【发布时间】:2013-04-22 23:10:58
【问题描述】:

我有一个 Autofac 作为 IoC 容器。我想为某些类型注册 Aspect。我可以这样做:

build.RegisterType(myType).As(ImyType).EnableInterfaceInterceptors().InterceptedBy(typeof(Aspect));

但是,如果我需要将拦截器注册到一定数量的类,而不是使用类型的拦截器,但它是实例。让我们看看我认为它应该是什么样子:

Aspect aspectInstance = new Aspect("some data to constructor")
build.RegisterType(myType).As(ImyType).EnableInterfaceInterceptors().InterceptedBy(aspectInstance);

我是使用 Ninject IoC 来做的。但是 Autofac 呢? 感谢任何预付款!

【问题讨论】:

    标签: c# .net ioc-container autofac aop


    【解决方案1】:

    查看the Autofac wiki page on Autofac.Extras.DynamicProxy2。它显示了一个 CallLogger 拦截器的示例,其中它将一个 lambda 注册为拦截器:

    var builder = new ContainerBuilder(); 
    builder.RegisterType<SomeType>()
           .As<ISomeInterface>()
           .EnableInterfaceInterceptors(); 
    builder.Register(c => new CallLogger(Console.Out));
    var container = builder.Build();
    var willBeIntercepted = container.Resolve<ISomeInterface>();
    

    对于您的情况,只需将其切换为注册实例即可。

    var builder = new ContainerBuilder(); 
    builder.RegisterType<SomeType>()
           .As<ISomeInterface>()
           .EnableInterfaceInterceptors()
           .InterceptedBy(typeof(Aspect));
    var interceptor = new Aspect();
    builder.RegisterInstance(interceptor);
    var container = builder.Build();
    var willBeIntercepted = container.Resolve<ISomeInterface>();
    

    或者,如果您不希望输入方面,则可以使用命名拦截器。

    var builder = new ContainerBuilder(); 
    builder.RegisterType<SomeType>()
           .As<ISomeInterface>()
           .EnableInterfaceInterceptors()
           .InterceptedBy("my-aspect-instance");
    var interceptor = new Aspect();
    builder.RegisterInstance(interceptor)
           .Named<IInterceptor>("my-aspect-instance");
    var container = builder.Build();
    var willBeIntercepted = container.Resolve<ISomeInterface>();
    

    再说一遍,check out the wiki - 有很多方法可以将拦截器与被拦截的类相关联,包括命名、类型、属性...... wiki 上有很多示例。

    【讨论】:

    • 非常感谢,这个有帮助。
    猜你喜欢
    • 2016-12-30
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多