首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将构造函数中有参数的侦听器用于Autofac InterceptorSelector

如何将构造函数中有参数的侦听器用于Autofac InterceptorSelector
EN

Stack Overflow用户
提问于 2018-12-15 01:16:17
回答 1查看 825关注 0票数 3

如何在有构造函数参数的IInterceptorSelector.SelectInterceptors方法中使用拦截器。我想让Autofac用它的参数解析我的拦截器,类似于这个Castle框架:

代码语言:javascript
复制
InterceptorReference.ForType<CallLogger>()

我对此进行了研究,但一无所获。

以下是摘自示例的示例代码:

代码语言:javascript
复制
class Program
{
    static void Main(string[] args)
    {
        var builder = new ContainerBuilder();
        var proxyGenerationOptions = new ProxyGenerationOptions();

        //I want to use this
        //proxyGenerationOptions.Selector = new InterceptorSelector();

        builder.RegisterType<SomeType>()
            .As<ISomeInterface>()
            .EnableInterfaceInterceptors(proxyGenerationOptions)

            .InterceptedBy(typeof(CallLogger));//and remove explicit statement

        builder.Register<TextWriter>(x => Console.Out);

        builder.RegisterType<CallLogger>().AsSelf();

        var container = builder.Build();

        var willBeIntercepted = container.Resolve<ISomeInterface>();
        willBeIntercepted.Work();
    }
}

public class InterceptorSelector : IInterceptorSelector
{
    public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
    {
        //don't know how to solve dependency here, because it's registration time
        return new IInterceptor[] { /* new CallLogger(dependency) or InterceptorReference.ForType<CallLogger>()  */};
    }
}

public class CallLogger : IInterceptor
{
    TextWriter _output;

    public CallLogger(TextWriter output)
    {
        _output = output;
    }

    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();

        _output.WriteLine("Done: result was {0}.", invocation.ReturnValue);
    }
}

public interface ISomeInterface { void Work(); }

public class SomeType : ISomeInterface { public void Work() { } }

我还想知道,Autofac中是否有任何动态拦截器分配机制。在Castle中,有多种方法可以修改拦截管道。

EN

回答 1

Stack Overflow用户

发布于 2018-12-15 08:16:38

目前,这在Autofac.Extras.DynamicProxy中是不可能的。您可以不使用拦截器选择器,而是从注册的元数据属性(由IntereceptedBy放在那里)检索拦截器。

我们已经有了one user note,你可以把你自己的拦截器连接起来,做一些类似这样的事情:

代码语言:javascript
复制
builder.RegisterType<Implementation>().AsSelf();
builder.Register(c =>
{
  ProxyGenerator proxyGen = new ProxyGenerator(true);
  return proxyGen.CreateInterfaceProxyWithTargetInterface<IInterfaceOfImplementation>(
    c.Resolve<Implementation>(),
    c.Resolve<ExceptionCatcherInterceptor>());
}).As<IInterfaceOfImplementation>();

这是一个更多的手册,但它可能会带你去你要去的地方。

I've added an enhancement issue来调查这件事。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53784205

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档