我的项目中有许多服务,并且尝试使用洗涤器进行自动DI,而不是手动在startup.cs上注册每个服务。
BarService.cs
public class BarService : IBar
{
public Bar Get(int id)
{
var bar = new Bar
{
bar_date = DateTime.UtcNow,
bar_name = "bar"
};
return bar;
}
public List<Bar> GetMany()
{
List<Bar> list = new List<Bar>
{
new Bar
{
bar_date = DateTime.UtcNow,
bar_name = "bar 1"
},
new Bar
{
bar_date = DateTime.UtcNow,
bar_name = "bar 2"
}
};
return list;
}
}IBar.cs
public interface IBar
{
Bar Get(int id);
List<Bar> GetMany();
}Bar.cs
public class Bar
{
public string bar_name { get; set; }
public DateTime bar_date { get; set; }
}BarController.cs
[Route("api/[controller]")]
[ApiController]
public class BarController : ControllerBase
{
public IBar _service { get; set; }
public BarController(IBar service)
{
_service = service;
}
[HttpGet("{id:int}")]
public IActionResult Get(int id)
{
var result = _service.Get(id);
if (result != null)
{
return Ok(result);
}
return NotFound("No data found");
}
[HttpGet]
public IActionResult GetMany()
{
var result = _service.GetMany();
if (result != null)
{
return Ok(result);
}
return NotFound("No data found");
}
}将services.AddScoped<IBar, BarService>();添加到Startup.cs可以很好,但使用Scrutor到自动映射就不行了。
services.Scan(scan =>
scan.FromCallingAssembly()
.AddClasses()
.AsMatchingInterface());我搞错了

发布于 2020-12-21 11:27:20
您目前使用的是AsMatchingInterface(),它
注册符合标准命名约定的服务。
这适用于下面这样的比赛。
public class BarService : IBarService在你的例子中
public class BarService : IBar不遵循该约定,因此不提供您预期的行为。
因此,要么重构您的接口以遵循Scrutor在抽象和实现之间的预期命名约定,
或者使用AsImplementedInterfaces(),其中
将实现注册为所有已实现的接口
但是,请注意,除非提供生存期,否则默认情况下,这将将这些接口注册为单例。
我建议把它们注册为范围。
发布于 2020-12-21 07:04:29
@Vikash,你可以试试AsImplementedInterfaces()。它将每个匹配的具体类型注册为其实现的所有接口。
services.Scan(scan =>
scan.FromCallingAssembly()
.AddClasses()
.AsImplementedInterfaces());结果如下所示。

https://stackoverflow.com/questions/65387894
复制相似问题