StructureMap返回动态代理

时间:2019-03-01 16:41:20

标签: c# inversion-of-control aop structuremap castle-dynamicproxy

您知道如何在StructureMap中创建一个返回动态代理的拦截器。到目前为止,这是我要尝试的操作,但是不起作用。

public class StructureMapTypeInterceptor : ISyncInterceptionBehavior
{
    private readonly IContainer _container;
    private readonly IAspectConfiguration _aspectConfiguration;
    private readonly ProxyGenerator _proxyGenerator;

    public StructureMapTypeInterceptor(IContainer container, IAspectConfiguration aspectConfiguration)
    {
        _container = container;
        _aspectConfiguration = aspectConfiguration;
        _proxyGenerator = new ProxyGenerator();
    }

    public IMethodInvocationResult Intercept(ISyncMethodInvocation methodInvocation)
    {         
        object target = methodInvocation.TargetInstance;
        Type targetType = target.GetType();

        var instanceRef = _container.Model.AllInstances.FirstOrDefault(e => e.ReturnedType == targetType);

        if (instanceRef != null)
        {
            Type interfaceToProxy = instanceRef.PluginType;

            if (interfaceToProxy.IsInterface)
            {
                object proxy = _proxyGenerator.CreateInterfaceProxyWithTargetInterface(interfaceToProxy, target, new[] { (IInterceptor)new AspectInterceptor(_aspectConfiguration) });

                return methodInvocation.CreateResult(proxy);
            }
        }

        return methodInvocation.CreateResult(target);
    }
}

这是注册

    var aspectTypeInterceptor = new StructureMapTypeInterceptor(ObjectFactory.Container, AspectConfiguration);
    ObjectFactory.Container
        .Configure(c => c.Policies
        .Interceptors(new DynamicProxyInterceptorPolicy(aspectTypeInterceptor)));

我让它在StructureMap 2中像这样工作:

public class StructureMapTypeInterceptor : TypeInterceptor
{
    private readonly IContainer _container;
    private readonly IAspectConfiguration _aspectConfiguration;
    private readonly ProxyGenerator _proxyGenerator;

    public StructureMapTypeInterceptor(IContainer container, IAspectConfiguration aspectConfiguration)
    {
        _container = container;
        _aspectConfiguration = aspectConfiguration;
        _proxyGenerator = new ProxyGenerator();
    }

    public object Process(object target, IContext context)
    {
        Type targetType = target.GetType();

        var instanceRef = _container.Model.AllInstances.FirstOrDefault(e => e.ConcreteType == targetType);

        if (instanceRef != null)
        {
            Type interfaceToProxy = instanceRef.PluginType;
            var proxy = _proxyGenerator.CreateInterfaceProxyWithTargetInterface(interfaceToProxy, target, new[] { (IInterceptor)new AspectInterceptor(_aspectConfiguration) });
            return proxy;
        }

        return target;
    }
}

但是在较新的版本中,他们删除了TypeInterceptor。您知道在较新的版本中还有其他选择吗?

0 个答案:

没有答案