在C#中,面向切面編程(AOP)的代理模式主要有兩種類型:靜態代理和動態代理。
示例代碼:
public interface IService
{
void DoWork();
}
public class Service : IService
{
public void DoWork()
{
Console.WriteLine("Service is working.");
}
}
public class ServiceProxy : IService
{
private readonly IService _service;
public ServiceProxy(IService service)
{
_service = service;
}
public void DoWork()
{
Console.WriteLine("Before service call.");
_service.DoWork();
Console.WriteLine("After service call.");
}
}
在C#中,可以使用System.Reflection.Emit
命名空間或第三方庫(如Castle DynamicProxy、LinFu等)來實現動態代理。
示例代碼(使用Castle DynamicProxy):
public interface IService
{
void DoWork();
}
public class Service : IService
{
public void DoWork()
{
Console.WriteLine("Service is working.");
}
}
public class ServiceInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("Before service call.");
invocation.Proceed();
Console.WriteLine("After service call.");
}
}
// 創建代理對象
var proxyGenerator = new ProxyGenerator();
var serviceProxy = proxyGenerator.CreateInterfaceProxyWithoutTarget<IService>(new ServiceInterceptor());
// 調用代理方法
serviceProxy.DoWork();
總結:靜態代理和動態代理各有優缺點,根據項目需求選擇合適的代理方式。