测试代码使用Autofac是好的,但是DryIoc是错误的。如何使这项工作。
public class HomeController : Controller
{
private readonly ITestAppService _testAppService;
private readonly IEnumerable<ITestAppService> _testAppServiceList;
public HomeController(ITestAppService testAppService, IEnumerable<ITestAppService> testAppServiceList)
{
_testAppService = testAppService;
_testAppServiceList = testAppServiceList;
}
}
public class Test1AppService : ITestAppService{}
public class Test2AppService : ITestAppService{}
public interface ITestAppService: IAppService{}
错误&#39;确保控制器具有无参数的公共构造函数&#39;是由控制器中的字段ITestAppService而不是IEnumerable字段引起的。以下是我的注册码。
var impls =
typeof(IAppService).Assembly
.GetTypes()
.Where(type =>
type.IsPublic &&
!type.IsAbstract &&
type.GetInterfaces().Length != 0 && typeof(IAppService).IsAssignableFrom(type));
foreach (var type in impls)
{
container.Register(type.GetInterfaces().First(), type, Reuse.Transient);
}
由dadhi的建议解决,我的容器是
DryIoc.IContainer container = new DryIoc.Container(
rules =>
{
return rules.WithFactorySelector(Rules.SelectLastRegisteredFactory())
.WithResolveIEnumerableAsLazyEnumerable();
}
);
关于从多个默认服务中解析的dryioc wiki可能需要一些更新。 Rules.SelectLastRegisteredFactory 是一种方法。
答案 0 :(得分:1)
问题在于导致ITestAppService
容器doesn't know which to select for the first dependency的两个实现。但您可以明确定义约定:
var container = new Container(rules => rules
.WithFactorySelector(Rules.SelectLastRegisteredFactory));