如何将OperationContract应用于接口中的所有方法 [英] how to apply OperationContract to all methods in interface

查看:300
本文介绍了如何将OperationContract应用于接口中的所有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在wcf应用程序中创建服务合同,其中包含许多方法.

Im creating a service contract in my wcf application and it contains a lot of methods.

我发现为所有人写一个OperationContract属性非常烦人.

I find it very annoying to write an OperationContract attribute to all of them.

有什么简单的方法可以说我的ServiceContract界面中的每个方法都是OperationContract"?

Is there any simple way how to say "every method in my ServiceContract interface is an OperationContract" ?

谢谢

推荐答案

是的,您可以为此使用AOP框架.例如.使用PostSharp:

Yes, you can use AOP framework for that. E.g. with PostSharp:

[Serializable]
public sealed class AutoServiceContractAttribute : TypeLevelAspect, IAspectProvider
{
    // This method is called at build time and should just provide other aspects.
    public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
    {
        Type targetType = (Type)targetElement;

        var introduceServiceContractAspect =
            new CustomAttributeIntroductionAspect( 
                new ObjectConstruction(typeof(ServiceContractAttribute)
                                          .GetConstructor(Type.EmptyTypes)));
        var introduceOperationContractAspect =
            new CustomAttributeIntroductionAspect( 
                new ObjectConstruction(typeof(OperationContractAttribute)
                                         .GetConstructor(Type.EmptyTypes)));

        // Add the ServiceContract attribute to the type.
        yield return new AspectInstance(targetType, introduceServiceContractAspect);

        // Add a OperationContract attribute to every relevant method.
        var flags = BindingFlags.Public | BindingFlags.Instance;
        foreach (MethodInfo method in targetType.GetMethods(flags))
        {
            if (!method.IsDefined(typeof(NotOperationContractAttribute), false))
                yield return new AspectInstance(method, introduceOperationContractAspect);
        }
    }
}

此属性用于标记不应作为操作合同的方法:

This attribute used to mark methods which should not be operation contracts:

[AttributeUsage(AttributeTargets.Method)]
public sealed class NotOperationContractAttribute : Attribute
{
}

现在您要做的就是将AutoServiceContract属性应用于服务接口.这将在接口中添加ServiceContract属性,所有公共方法都将标记为OperationContact属性(具有NotOperationContract属性的方法除外)

Now all you need to do is apply AutoServiceContract attribute to service interface. That will add ServiceContract attribute to interface, and all public methods will be marked with OperationContact attribute (except those which have NotOperationContract attribute):

[AutoServiceContract]
public interface IService1
{
    public void Method1();
    [NotOperationContact]
    public string Method2);
    public int Method3(int a);
    // ...
}

这篇关于如何将OperationContract应用于接口中的所有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆