我有一些类接受返回对象的委托,比如:
public class ApiAuditor : IAuditor
{
public Func<FooAPI> ApiGet { get; private set; }
public ApiAuditor(Func<FooAPI> apiGet)
{
ApiGet = apiGet;
}
public bool Audit(Audit[] audits)
{
if(someCondition)
return false; //no need for FooAPI
return ApiGet().AuditJobs(audits);
}
}
其想法是,其中一些类可能需要一个对象实例(在本例中为FooAPI),但并不总是如此。因此,它们被注入为一个委托,如果需要,可以返回一个实例。
使用Ninject,我只是想看看像这样绑定这种类型是否是最好的方法?
Bind<IAuditor>().ToMethod(c => new ApiAuditor(() => c.Kernel.Get<FooAPI>()));
更新
更详细地说,我想我的部分问题是,每当构造函数参数需要显式解决时,我都会使用Bind.WithConstructorArgument()。我想我仍然可以使用它,但它的可读性较差,因为它最终会变成这样:
Bind<IAuditor>().To<ApiAuditor>().WithConstructorArgument("apiGet", x => ( (Func<FooAPI>)(() => x.Kernel.Get<FooAPI>())));
防止自己连接实例。您可以执行以下操作:
kernel.Bind<IApiAuditor>().To<ApiAuditor>();
kernel.Bind<Func<FooAPI>>().ToConstant(() => kernel.Get<FooAPI>()));
请注意,您通常不应该担心注入未使用的实例。性能损失通常是可以忽略的,所以您应该简单地创建以下构造函数:
public ApiAuditor(FooAPI foo)
{
this.foo = foo;
}
这使您的注册更容易:
Bind<IApiAuditor>().To<ApiAuditor>();
Bind<FooAPI>().ToSelf();