class Program
{
static void Main(string[] args)
{
//建立一個容器
ContainerBuilder builder = new ContainerBuilder();
//註冊UserService
builder.RegisterType<UserService>().As<IUserService>()
.EnableInterfaceInterceptors();//透過介面方式完成aop擴充套件
builder.RegisterType<CustomInterceptor>();//透過介面方式完成aop擴充套件
//從容器中解析出UserService
IContainer container = builder.Build();
IUserService a = container.Resolve<IUserService>();
//執行UserService的方法
a.show();
}
}
//生產一個 UserService類
public class UserService : IUserService
{
public void show()
{
Console.WriteLine("UserService 執行");
}
}
[Intercept(typeof(CustomInterceptor))]//透過介面方式完成aop擴充套件
public interface IUserService
{
void show();
}
using Castle.DynamicProxy; namespace autofac_aop測試; public class CustomInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { Console.WriteLine("================================================"); Console.WriteLine("=================在XX業務邏輯前執行=============="); Console.WriteLine("================================================="); invocation.Proceed(); Console.WriteLine("==================================================="); Console.WriteLine("=================在XX業務邏輯後執行================"); Console.WriteLine("==================================================="); } }