Ninject C# 中的工厂方法
Factory methods in Ninject C#
我有一个名为 IBreakfastProvider 的接口,它有多个实现。目前,我的代码根据 id 决定使用哪一个。它使用工厂方法,如下所示:
public IBreakfastProvider GetBreakfastProvider(int id)
{
switch (id)
{
case 1:
return new CornFlakeProvider(new SomeDependency());
case 2:
return new MuesliProvider(new SomeOtherDependency());
case 3:
return new ToastProvider();
default:
throw new ApplicationException("Unknown provider id.");
}
}
IBreakfast 提供程序的每个实现都可以有自己的依赖项。如何替换此方法以使用 Ninject 根据此整数 ID 计算出要使用的实现?
您可以为每种类型注册一个名称。然后,当您需要解析时,只需将 id
传递给 Ninject:
// Use better naming though :)
kernel.Bind<IBreakfastProvider>().To<CornFlakeProvider>().Named("1");
然后当你解决:
var breakfastProvider = resolutionRoot.Get<IFoo>(id);
使用构造函数注入:
public class BreakfastProviderFactory
{
private readonly CornFlakeProvider provider1;
private readonly MuesliProvider provider2;
private readonly ToastProvider provider3;
public BreakfastProviderFactory(CornFlakeProvider provider1,
MuesliProvider provider2, ToastProvider provider3) {
{
this.provider1 = provider1;
this.provider2 = provider2;
this.provider3 = provider3;
}
public IBreakfastProvider GetBreakfastProvider(int id)
{
switch (id)
{
case 1: return this.provider1;
case 2: return this.provider2;
case 3: return this.provider3;
default: throw new ApplicationException("Unknown provider id.");
}
}
}
我有一个名为 IBreakfastProvider 的接口,它有多个实现。目前,我的代码根据 id 决定使用哪一个。它使用工厂方法,如下所示:
public IBreakfastProvider GetBreakfastProvider(int id)
{
switch (id)
{
case 1:
return new CornFlakeProvider(new SomeDependency());
case 2:
return new MuesliProvider(new SomeOtherDependency());
case 3:
return new ToastProvider();
default:
throw new ApplicationException("Unknown provider id.");
}
}
IBreakfast 提供程序的每个实现都可以有自己的依赖项。如何替换此方法以使用 Ninject 根据此整数 ID 计算出要使用的实现?
您可以为每种类型注册一个名称。然后,当您需要解析时,只需将 id
传递给 Ninject:
// Use better naming though :)
kernel.Bind<IBreakfastProvider>().To<CornFlakeProvider>().Named("1");
然后当你解决:
var breakfastProvider = resolutionRoot.Get<IFoo>(id);
使用构造函数注入:
public class BreakfastProviderFactory
{
private readonly CornFlakeProvider provider1;
private readonly MuesliProvider provider2;
private readonly ToastProvider provider3;
public BreakfastProviderFactory(CornFlakeProvider provider1,
MuesliProvider provider2, ToastProvider provider3) {
{
this.provider1 = provider1;
this.provider2 = provider2;
this.provider3 = provider3;
}
public IBreakfastProvider GetBreakfastProvider(int id)
{
switch (id)
{
case 1: return this.provider1;
case 2: return this.provider2;
case 3: return this.provider3;
default: throw new ApplicationException("Unknown provider id.");
}
}
}