查看DryIoc的wiki,看起来这些例子显示了我需要的东西的相反方向,我想知道是否可能出现相反情况?DryIoc Register接口的很多实现
维基(部分示例)
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."
这是可能的开箱或者我需要通过从一个程序集中获取接口的所有实现并对其进行循环来实现它并相应注册?
UPDATE
我看到这个例子是也许有点简单了我的情况,但对于上面的例子,@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容器。 Thnxs提前。 :)
我看到更新代码中的问题:'type => type.IsAssignableTo(typeof(IImporter))&& type.IsClass &&!type.IsAbstract' – dadhi
该条件适用于**服务类型**,不适用于实现类型。因此'type => type == typeof(IImporter)'就足够了,如果你想注册为'Register()'等,或者使它成为'type => type.IsAssignableTo(typeof(IImporter) )&& type.IsInterface'用于注册所有'IImporter'派生的接口。回到你的谓词,它将注册具体类型,而不是'Register ()'。 –
dadhi