我为使用 ASP.NET Webforms 的旧 SharePoint On-Prem 项目创建了一个简单的程序作为 PoC。在它的页面中,我必须使用属性注入,而对于其他一切,我可以使用构造函数注入。我也在使用:
- Ninject.Extensions.Factory
- Ninject.Extensions.Interception
- Ninject.Extensions.Interception.DynamicProxy
在我添加拦截器并使用 Lazy<> 处理一些循环依赖之前,一切都运行得相对较好。为了在示例中简化这一点,我将以下示例编写为控制台应用程序:
public class Program
{
static void Main(string[] args)
{
IKernel kernel = new StandardKernel(
new NinjectSettings() { LoadExtensions = false },
new DynamicProxyModule(),
new FuncModule());
kernel.Bind<ISomeClass>().To<SomeClass>();
kernel.Bind<IOtherClass>().To<OtherClass>();
kernel.Bind<IAnotherClass>().To<AnotherClass>();
kernel.Intercept(p => true).With(new ClassInterceptor()); // Removing this works, but I need the interceptors.
ISomeClass someClass = kernel.TryGet<ISomeClass>();
someClass.Foo();
}
public interface ISomeClass
{
void Foo();
}
public class SomeClass : ISomeClass
{
[Inject]
public IOtherClass OtherClass { get; set; }
public SomeClass() { }
public void Foo()
{
Console.WriteLine("Foo");
this.OtherClass.Bar();
}
}
public interface IOtherClass
{
void Bar();
}
public class OtherClass : IOtherClass
{
private readonly Lazy<IAnotherClass> _anotherClass;
public IAnotherClass AnotherClass { get { return this._anotherClass.Value; } }
public OtherClass(Lazy<IAnotherClass> anotherClass)
{
this._anotherClass = anotherClass;
}
public void Bar()
{
Console.WriteLine("Bar");
}
}
public interface IAnotherClass
{
void FooBar();
}
public class AnotherClass : IAnotherClass
{
private readonly Lazy<IOtherClass> _otherClass;
public IOtherClass OtherClass { get { return this._otherClass.Value; } }
public AnotherClass(Lazy<IOtherClass> otherClass)
{
this._otherClass = otherClass;
}
public void FooBar()
{
Console.WriteLine("FooBar");
this.OtherClass.Bar();
}
}
public class ClassInterceptor: SimpleInterceptor
{
public ClassInterceptor() { }
protected override void BeforeInvoke(IInvocation invocation)
{
base.BeforeInvoke(invocation);
Console.WriteLine("I'm doing stuff before.");
}
protected override void AfterInvoke(IInvocation invocation)
{
base.BeforeInvoke(invocation);
Console.WriteLine("I'm doing stuff after.");
}
}
}
结果,我收到以下错误:
未处理的异常:System.TypeLoadException:无法从程序集“DynamicProxyGenAssembly2,Version=0.0.0.0,Culture=neutral,PublicKeyToken=a621a9e7e5c32e69”加载类型“Castle.Proxies.Func`2Proxy”,因为父类型是密封的。
如果我删除“Lazy<>”,它将重新引入循环依赖。如果我删除拦截,它不会有任何错误,但我需要拦截器。而且,我必须在页面上使用属性注入,因为页面的构造函数是由 webforms 管理的,没有像 MVC 领域那样有用的钩子。注意:由于使用的是 SharePoint 2013,因此使用了 Web 表单。
任何想法如何在不遇到上述错误的情况下同时保留拦截和 Lazy<> 声明?