查看 DryIoc的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>();
...
Run Code Online (Sandbox Code Playgroud)
我想做以下事情
container.RegisterMany<X>();
// This would return one implementation each of A and B
container.ResolveMany<X>();
Run Code Online (Sandbox Code Playgroud)
然而,这给出了这个错误: "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>();
}
}
}
Run Code Online (Sandbox Code Playgroud)
像这样的东西可以开箱即用吗?或者我需要制作自己的扩展方法等吗?真的不会有那么大的麻烦,我可能会在短时间内完成它,但是我想知道以供将来参考并学习 DryIoc 容器。提前谢谢。:)
有RegisterMany接受程序集和服务类型条件的重载(wiki中的示例之一):
container.RegisterMany(new[] { typeof(A).Assembly },
serviceTypeCondition: type => type == typeof(X));
Run Code Online (Sandbox Code Playgroud)
以上从 A 的汇编中注册了 X 的所有实现。
| 归档时间: |
|
| 查看次数: |
2299 次 |
| 最近记录: |