Ninject:每个Get调用调用一个方法

问题描述 投票:1回答:1

我在Ninject上有一个Singleton Binding,我想在DI解析时调用一个方法(即每次Get调用)。 Ninject具有OnActivation方法,该方法仅在解析对象时调用。

我知道使用Transient范围将是直观的解决方案,但由于失控的原因。对象必须是单例。

c# .net dependency-injection ninject
1个回答
1
投票

你可以用一些技巧来达到这个目的。让我给你举个例子:

const string Name = "Foo";

// Singleton Binding. Will only be used when the context uses the {Name}
Bind<Foo>().To<Foo>()
    .Named(Name)
    .InSingletonScope();

// Unnamed binding with method call on each resolution
Bind<Foo>().ToMethod(ctx => 
    {
        // Do anything arbitrary here. like calling a method...
        return ctx.Kernel.Get<Foo>(Name));
    });

当从内核请求Foo(未命名)时,它将解析为ToMethod绑定 - 您可以在其中插入任何您喜欢的任意代码。最后,该方法必须使用内核来请求Foo,但这次使用了name-condition。这将解析为命名的单例绑定。

© www.soinside.com 2019 - 2024. All rights reserved.