我试图创建类似IAuditable接口的东西,它充当Ninject拦截调用的标记.
public interface IAuditable { } public interface IProcessor { void Process(object o); } public class Processor : IProcessor,IAuditable { public void Process(object o) { Console.WriteLine("Processor called with argument " + o.ToString()); } }
使用此设置:
NinjectSettings settings = new NinjectSettings() { LoadExtensions = true }; IKernel kernel = new StandardKernel(settings); kernel.Bind<IAuditAggregator>().To<AuditAggregator>().InThreadScope(); kernel.Bind<IAuditInterceptor>().To<AuditInterceptor>(); kernel.Bind(x => x.FromThisAssembly() .SelectAllClasses() .InheritedFrom<IAuditable>() .BindToDefaultInterfaces() //I SUSPECT I need something else here .Configure(c => c.Intercept().With<IAuditInterceptor>())); kernel.Bind<IProcessor>().To<Processor>();
每当我尝试kernel.Get< IProcessor>();我得到一个例外,告诉我有多个绑定可用.
如果我删除kernel.Bind< IProcessor>().到< Processor>()然后它按预期工作,但你可能有一个不实现IAuditable的IProcessor.
我是在正确的轨道上吗?
编辑:建议我尝试使用属性:
public class AuditableAttribute : Attribute { } [Auditable] public class Processor : IProcessor { public void Process(object o) { Console.WriteLine("Processor called with argument " + o.ToString()); } } //in setup: kernel.Bind(x => x.FromThisAssembly() .SelectAllClasses() .WithAttribute<AuditableAttribute>() .BindDefaultInterface() .Configure(c => c.Intercept().With<IAuditInterceptor>()));
这导致与使用接口相同的重复绑定问题.
解决方法
您应该能够为实现IAuditable的类型编写一个约定绑定,为未实现的类型编写一个约定绑定.
kernel.Bind(x => x.FromThisAssembly() .SelectAllClasses() .InheritedFrom<IAuditable>() .BindDefaultInterfaces() .Configure(c => c.Intercept().With<IAuditInterceptor>())); kernel.Bind(x => x.FromThisAssembly() .SelectAllClasses() .InheritedFrom<IProcessor>() .Where(t => !typeof(IAuditable).IsAssignableFrom(t)) .BindDefaultInterfaces());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。