Unity拦截配置 - 如何减少冗长?

时间:2011-05-26 09:08:38

标签: .net configuration unity-container app-config configuration-files

要在Unity 2.0中设置拦截,请在配置中添加这样的内容(取自Unity文档)...

      <policy name="addDataAccessTypes">
        <matchingRule name="DataLayerMatch" type="NamespaceMatchingRule">
          <constructor>
            <param name="namespaceName" value="MyApp.DataAccess" />
          </constructor>
        </matchingRule>
        <callHandler name="LogHandler" type="LoggingCallHandler" />
        <callHandler name="SecurityHandler"
            type="DatabaseSecurityCheckHandler" />
      </policy>

有没有办法为相同的处理类设置多个接口?

E.g。像这样......

<constructor>
    < interface to intercept 1 />
    < interface to intercept 2 />
</construtor>

使用unity示例中给出的方法,如果有很多接口可以拦截,那么配置文件会变得非常冗长。

1 个答案:

答案 0 :(得分:2)

如果使用Unity.Interception程序集,则可以更流畅地对属性进行拦截。这样做的缺点是截获的类(以某种方式)知道方面:

设置的一个非常快速的示例如下所示:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine();
            Console.WriteLine("Starting test...");

            var container = new UnityContainer();
            container.AddNewExtension<Interception>();
            container.Configure<Interception>()
                .SetDefaultInterceptorFor<IGadget>(new InterfaceInterceptor());

            container.RegisterType<IGadget, Gadget>();

            var gadget = container.Resolve<IGadget>();
            gadget.DoSomething();
        }
        catch (Exception ex)
        {
            Console.WriteLine();
            Console.WriteLine("An error has occurred: {0}", ex);
        }
        finally
        {
            Console.WriteLine();
            Console.WriteLine("Test complete.");
            Console.ReadKey();
        }
    }
}



public class LogAttribute : HandlerAttribute
{
    public override ICallHandler CreateHandler(IUnityContainer container)
    {
        return container.Resolve<LogHandler>();
    }
}

public class LogHandler : ICallHandler
{
    public int Order { get; set; }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        Console.WriteLine("*** Logging the action! -{0}-", input.MethodBase.Name);
        return getNext()(input, getNext);
    }
}

public interface IGadget
{
    void DoSomething();
}

[Log]
public class Gadget : IGadget
{
    public void DoSomething()
    {
        Console.WriteLine("\tI did something!");
    }
}