我刚刚开始使用IoC容器,如果这是一个愚蠢的问题,请道歉.
我在应用程序中有如下代码
internal static class StaticDataHandlerFactory
{
public static IStaticDataHandler CreateHandler(StaticDataUpdate staticDataUpdate)
{
if (staticDataUpdate.Item is StaticDataUpdateOffice)
{
return new OfficeUpdateHandler();
}
if (staticDataUpdate.Item is StaticDataUpdateEmployee)
{
return new EmployeeUpdateHandler();
}
if (staticDataUpdate.Item == null)
{
throw new NotImplementedException(
string.Format("No static data provided"));
}
else
{
throw new NotImplementedException(
string.Format("Unimplemented static data type of {0}", staticDataUpdate.Item.GetType().FullName));
}
}
}
Run Code Online (Sandbox Code Playgroud)
它基本上是一个简单的工厂,它返回处理输入数据的正确策略.
IoC容器是否允许我删除这样的代码?也就是说:它是否允许我根据输入参数的类型动态选择要加载的具体实现?
还是我离开这里?
是否可能和/或一个好主意使用Ninject(或任何其他IoC容器)为不存在适当实现的情况创建默认绑定,并使用此默认绑定而不是必须处理ActivationException当存在多个绑定,或者特定请求没有绑定时?
我一直在使用Ninject的工厂和公约扩展项目,但我想知道他们是否正在掩盖我在更基础的层面上犯的错误,所以我创建了一个测试来说明我想要做的事情,因为我尽我所能:
鉴于以下内容:
public interface IWidget { }
public class DefaultWidget : IWidget { }
public class BlueWidget : IWidget { }
Run Code Online (Sandbox Code Playgroud)
以下使用FluentAssertions进行xUnit测试:
[Fact]
public void Unknown_Type_Names_Resolve_To_A_Default_Type()
{
StandardKernel kernel = new StandardKernel();
// intention: resolve a `DefaultWidget` implementation whenever the
// 'name' parameter does not match the name of any other bound implementation
kernel.Bind<IWidget>().To<DefaultWidget>();
kernel.Bind<IWidget>().To<BlueWidget>().Named(typeof(BlueWidget).Name);
kernel.Get<IWidget>("RedWidget").Should().BeOfType<DefaultWidget>();
// ACTIVATION EXCEPTION (**NO matching bindings available** for `IWidget`)
} …Run Code Online (Sandbox Code Playgroud) dependency-injection anti-patterns ninject ioc-container service-locator