gpt4 book ai didi

c# - 当简单注入(inject)器只有一个具体时,如何让它自动解析接口(interface)?

转载 作者:行者123 更新时间:2023-11-30 13:30:49 25 4
gpt4 key购买 nike

目前我有一个带有这样构造函数的 webapi Controller :

readonly IQueryFactory queryFactory;
readonly ICommandFactory commandFactory;

public UserBenefitsController(
IQueryFactory queryFactory,
ICommandFactory commandFactory)
{
this.queryFactory = queryFactory;
this.commandFactory = commandFactory;
}

我正在使用简单的注入(inject)器来注册这两种类型。

container.RegisterWebApiRequest<IQueryFactory, QueryFactory>();
container.RegisterWebApiRequest<ICommandFactory, CommandFactory>();

但我发现,随着我继续开发我的应用程序,我继续有很多 ISomeInterface 以 1:1 的比例解析为 ISomeConcrete

当 WebApiRequest 范围内只有 1 个具体的接口(interface)时,是否可以告诉简单的注入(inject)器查找接口(interface)并自动解析它?

最佳答案

您可以使用批处理/自动注册来解析具体实例。Simple Injector 文档对其进行了解释 here

例如:

ScopedLifestyle scopedLifestyle = new WebApiRequestLifestyle();

var assembly = typeof(YourRepository).Assembly;

var registrations =
from type in assembly.GetExportedTypes()
where type.Namespace == "Acme.YourRepositories"
where type.GetInterfaces().Any()
select new
{
Service = type.GetInterfaces().Single(),
Implementation = type
};

foreach (var reg in registrations)
container.Register(reg.Service, reg.Implementation, scopedLifestyle);

关于c# - 当简单注入(inject)器只有一个具体时,如何让它自动解析接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26934325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com