给出以下代码:
using Castle.DynamicProxy;
using Castle.Facilities.TypedFactory;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using System;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
WindsorContainer container = new WindsorContainer();
container.AddFacility<TypedFactoryFacility>();
container.Register(Classes.FromThisAssembly()
.BasedOn<IAuditInterceptor>()
.WithServiceDefaultInterfaces()
.LifestyleTransient());
container.Register(Classes.FromThisAssembly()
.BasedOn(typeof(ICommandHandler<>))
.WithServiceAllInterfaces()
.Configure(c => c.Interceptors<IAuditInterceptor>().LifestyleTransient()));
container.Register(Component.For<ICommandHandlerFactory>().AsFactory());
var factory = container.Resolve<ICommandHandlerFactory>();
var handlers = factory.GetHandlersForCommand<DummyCommand>();
handlers.First().Handle(new DummyCommand());
}
}
public interface IAuditInterceptor : IInterceptor
{
}
public interface ICommand
{
}
public interface ICommandHandler<T> where T : ICommand
{
void Handle(T command);
}
public interface ICommandHandlerFactory
{
ICommandHandler<T>[] GetHandlersForCommand<T>() where T : ICommand;
}
public class DummyCommand : ICommand
{
}
public class DummyCommandHandler : ICommandHandler<DummyCommand>
{
public void Handle(DummyCommand command)
{
Console.WriteLine("Hello from command handler");
}
}
public class AuditInterceptor : IAuditInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("Interceptor before");
invocation.Proceed();
Console.WriteLine("Interceptor After");
}
}
}
代码按预期运行并执行,拦截器触发,程序正常完成。但是,如果您检查可能配置错误的组件,则会被告知
无法静态解析此组件的某些依赖项。 'ConsoleApplication1.DummyCommandHandler'正在等待以下内容 依赖关系: - 组件'ConsoleApplication1.IAuditInterceptor'(通过覆盖)找不到。你有没有忘记注册或拼错了 名称?如果组件已注册,则覆盖是通过类型make 确定它没有明确指定的非默认名称或覆盖 依赖名称。
是什么原因引起的?代码运行并执行没有问题。为什么温莎说它找不到IAuditInterceptor
?
如果删除IAuditInterceptor
的注入并单独注册具体类型AuditInterceptor
,则会消失,如下所示:
container.Register(Component.For<AuditInterceptor>().LifestyleTransient());
container.Register(Classes.FromThisAssembly()
.BasedOn(typeof(ICommandHandler<>))
.WithServiceAllInterfaces()
.Configure(c => c.Interceptors<AuditInterceptor>().LifestyleTransient()));