使用SimpleIoc我想自动注册实现特定接口的所有类。我无法在SimpleIoc的容器上看到一个方法来自动执行此操作,因此我将一些代码放在一起以迭代要注册的类型。不幸的是,代码并不满意(请参阅注释行)。
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(typeof(IFoo).IsAssignableFrom);
foreach (var type in types.Where(x=>x.IsClass))
{
container.Register<IFoo, type>(); //this line won't compile as type can't be resolved by the compiler
}
我意识到注册类的方式不那么优雅(比如硬编码&#34; container.Register&#34;将每个类注册到界面)但是我希望能够添加新的实现而不必继续更新ioc安装程序代码。在某些时候,使用相同的方法在其他程序集中注册类也是有用的。
知道我需要改变什么才能进行这种构建(或者有更简单/更优雅的方式来做到这一点)?
更新 fex发布了此评论:
"you can always iterate over types (like you do in your question) and create it with reflection (in your factory class) - (IFoo)Activator.CreateInstance(type); - in fact that's how service locators / ioc containers do it internally (in simplify)."
我现在已经将我的代码更新为以下代码,但有一点需要注意(实现必须有一个无参数构造函数,因此必须由工厂满足依赖关系,然后我用它来提供服务实现IFoo的实例)。我也提供了工厂注册信息。
更新的代码:
// Get the types that implement IFoo...
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(typeof(IFoo).IsAssignableFrom);
// Register these types and use reflection to instantiate each instance...
foreach (var type in types.Where(x=>x.IsClass))
{
var t = type;
container.Register(() => (IFoo)Activator.CreateInstance(t), t.ToString());
}
// Inject all registered instances of IFoo into IFooFactory when it's instantiated.
// Note that instances of IFoo must have their own dependencies satisfied via the
// factory at runtime before being served by the factory.
container.Register<IFooFactory>(
() => new FooFactory(container.GetAllInstances<IFoo>()));