我可能对ActivationStrategy
的行为有一些误解。以下是解释它的代码:
void Main()
{
var kernel = new StandardKernel();
kernel.Settings.AllowNullInjection = true;
kernel.Components.Add<IActivationStrategy, NinjectLoggingStrategy>();
kernel.Bind<C>().ToProvider(new CallbackProvider<C>(ctx =>
{
// return null;
return new C();
}));
kernel.Get<A>();
}
public class A {public A(B b){}}
public class B {public B(C c){}}
public class C {}
public class NinjectLoggingStrategy : ActivationStrategy
{
private static string RequestPath(IRequest request)
{
if (request == null) return "";
var parentRequest = request.ParentRequest;
return RequestPath(parentRequest) + " => " + request.Service.Name;
}
public override void Activate(IContext context, InstanceReference reference)
{
var parentRequest = context.Request.ParentRequest;
var parentReference = parentRequest == null ? "" : parentRequest.Service.FullName;
Console.WriteLine("Activating: " + reference.Instance.GetType().FullName);
Console.WriteLine("Activation Path: " + RequestPath(context.Request));
base.Activate(context, reference);
}
}
结果是:
Activating: UserQuery+C
Activation Path: => A => B => C
Activating: UserQuery+B
Activation Path: => A => B
Activating: UserQuery+A
Activation Path: => A
上面是Linqpad中编写的整个代码,请注意CallBackProvider中返回null的行,此行现已注释掉。
// return null;
如果我取消评论此行,结果将是:
Activating: UserQuery+B
Activation Path: => A => B
Activating: UserQuery+A
Activation Path: => A
我的理解是,无论激活结果如何,都应始终调用ActivationStrategy。