查看 DryIoc 的 wiki,这些示例似乎显示了我需要的相反内容,我想知道相反是否可能?
Wiki (部分示例)
public interface X {}
public interface Y {}
public class A : X, Y {}
public class B : X, IDisposable {}
// Registers X, Y and A itself with A implementation
container.RegisterMany<A>();
...
我想做以下事情
container.RegisterMany<X>();
// This would return one implementation each of A and B
container.ResolveMany<X>();
然而,这给出了这个错误:
"Registering abstract implementation type X when it is should be concrete. Also there is not FactoryMethod to use instead."
这是否可以开箱即用,或者我是否需要通过从程序集中获取接口的所有实现并对其进行循环并相应地注册来自己实现它?
更新
我发现这个示例对于我的情况来说可能有点简单,但对于上面的示例,@dadhi 提供的代码效果很好。
这是一个更“复杂”的情况
namespace Assembly.A
{
interface IImporter { }
abstract class ImporterBase : IImporter { }
}
namespace Assembly.B
{
interface IStuffImporter : IImporter { }
interface IOtherImporter : IImporter { }
class StuffImporter : ImporterBase, IStuffImporter { }
class OtherImporter : ImporterBase, IOtherImporter { }
}
namespace Assembly.C
{
class Program
{
void Main()
{
var container = new Container();
container.RegisterMany( new[] { typeof(StuffImporter).Assembly }, type => type.IsAssignableTo(typeof(IImporter)) && type.IsClass && !type.IsAbstract);
//I would like DryIoc to do the following behind the scenes
//container.Register<IStuffImporter, StuffImporter>();
//container.Register<IOtherImporter, OtherImporter>();
var importers = container.ResolveMany<IImporter>();
importers.Should().HaveCount(2);
importers.First().Should().BeOfType<StuffImporter>().And.BeAssignableTo<IStuffImporter>();
importers.Last().Should().BeOfType<OtherImporter>().And.BeAssignableTo<IOtherImporter>();
}
}
}
这样的事情可以开箱即用吗?或者我是否需要制作自己的扩展方法等?这实际上不会有那么大的麻烦,而且我可能会在短时间内完成它,但是我想知道以供将来参考和学习DryIoc 容器。提前谢谢。 :)
存在
RegisterMany
重载,它接受程序集和服务类型条件(wiki中的示例之一):
container.RegisterMany(new[] { typeof(A).Assembly },
serviceTypeCondition: type => type == typeof(X));
上面注册了 A 汇编中 X 的所有实现。
@dadhi 接受的答案并不完全适合我。 这就是我让它按预期工作的方法。
container.RegisterMany(
typeof(A).Assembly.GetImplementationTypes(),
serviceTypeCondition: type => type.GetInterfaces().Any(i => i == typeof(X))
);