我想记录用户界面方法的调用。
我的想法是拦截继承自System.Windows.Forms.Form的MyUserInterface类。
但是,我得到了 TypeLoadException:来自程序集“DynamicProxyGenAssembly2”的类型“Castle.Proxies.IComponentProxy”正在尝试实现无法访问的接口
如何解决这个问题?
我在注册时遗漏了什么吗?
谢谢!
using System;
using Autofac;
using Autofac.Extras.DynamicProxy;
using Castle.DynamicProxy;
public class Program
{
public static void Main()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<MyInterceptor>();
builder.RegisterType<MyUserInterface>().As<IMyUserInteraface>()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(MyInterceptor));
var container = builder.Build();
var ui = container.Resolve<IMyUserInteraface>();
ui.Show();
}
}
public class MyInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("UI intercepted and logged");
invocation.Proceed();
}
}
//If MyUserInterface inherit Form, will get TypeLoadException.
//TypeLoadException: Type 'Castle.Proxies.IComponentProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.
//public class MyUserInterface : Form, IMyUserInteraface
public class MyUserInterface : IMyUserInteraface
{
public void Show()
{
Console.WriteLine("Show something");
}
}
public interface IMyUserInteraface
{
void Show();
}
我曾尝试删除继承表格。然后就可以了。 但MyUserInterface必须继承自Form。
目前,通过在ProxyGenerator中使用CreateInterfaceProxyWithTarget解决。
using System;
using Autofac;
using Autofac.Extras.DynamicProxy;
using Castle.DynamicProxy;
using System.Windows.Forms;
public class Program
{
public static void Main()
{
var builder = new ContainerBuilder();
//builder.RegisterType<MyInterceptor>();
//builder.RegisterType<MyUserInterface>().As<IMyUserInteraface>()
// .EnableInterfaceInterceptors()
// .InterceptedBy(typeof(MyInterceptor));
var generator = new ProxyGenerator();
var myUserInterface = new MyUserInterface();
var userInterfaceProxy = generator.CreateInterfaceProxyWithTarget<IMyUserInteraface>(myUserInterface, new MyInterceptor());
builder.RegisterInstance(userInterfaceProxy).As<IMyUserInteraface>();
var container = builder.Build();
var ui = container.Resolve<IMyUserInteraface>();
ui.Run();
}
}
public class MyInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("UI intercepted and logged");
invocation.Proceed();
}
}
public class MyUserInterface : Form, IMyUserInteraface
{
public void Run()
{
Console.WriteLine("Show something");
}
}
public interface IMyUserInteraface
{
void Run();
}