Dynamic Proxy

How to make a simple dynamic proxy in C#

You could do this with a combination of System.Dynamic.DynamicObject and ImpromptuInterface but you will have to have an Interface that implements the functions and properties you want to proxy.

https://docs.microsoft.com/en-us/dotnet/api/system.dynamic.dynamicobject?redirectedfrom=MSDN&view=netframework-4.8

https://github.com/ekonbenefits/impromptu-interface

复制代码
public interface IDoStuff
{
    void Foo();
}

public class Wrapper<T> : DynamicObject
{
    private readonly T _wrappedObject;

    public static T1 Wrap<T1>(T obj) where T1 : class
    {
        if (!typeof(T1).IsInterface)
            throw new ArgumentException("T1 must be an Interface");

        return new Wrapper<T>(obj).ActLike<T1>();
    }

    //you can make the contructor private so you are forced to use the Wrap method.
    private Wrapper(T obj)
    {
        _wrappedObject = obj;
    }

    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        try
        {
            //do stuff here

            //call _wrappedObject object
            result = _wrappedObject.GetType().GetMethod(binder.Name).Invoke(_wrappedObject, args);
            return true;
        }
        catch
        {
            result = null;
            return false;
        }
    }
}
复制代码

You could off course choose to lose the type-safety and go with a DynamicObject like I showed and then drop the duck-casting.

I made a transparant extendible version of this object proxy, and opensourced it here.

https://github.com/Curit/DynamicProxy

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(336)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2017-05-20 Create an ASP.NET Core web app in Visual Studio Code
2017-05-20 CSS元素选择器 element selector(type selector)
2017-05-20 如何查看本机正在监听的端口
2017-05-20 Error 0x80070020 when you try to start a Web site in IIS 7.0
点击右上角即可分享
微信分享提示