gpt4 book ai didi

c# - CaSTLe.Windsor - 为什么名称需要与界面相似?

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:26 25 4
gpt4 key购买 nike

当我尝试在我的 ASP.NET MVC 应用程序中创建一个新的 HangFire 作业时,我注意到了这个有趣的场景。

// this is the interface for the HangFire job.
public interface ICsvExportService
{
void ExportCsvToEmail();
}

// this is the implementation of the above interface.
public class ExportService : ICsvExportService
{
// code goes here.
}


RecurringJob.RemoveIfExists("My CSV exports");
RecurringJob.AddOrUpdate<ICsvExportService>(
"Send CSV exports",
x => x.ExportCsvToEmail(),
Cron.Daily(8));

当我尝试在本地对此进行测试时,出现以下错误:

抛出异常:HangFire.Core.dll 中的“CaSTLe.MicroKernel.ComponentNotFoundException”
未找到支持服务 ICsvExportService 的组件。


在尝试不同的解决方案 30 分钟后,我将文件重命名为:ExportService 为 CsvExportService,奇迹发生了!有效!

有人能解释一下为什么我需要使用与接口(interface)相同的名称以使 DI 容器识别实际的实现类吗?

.NET 4.5 的 CaSTLe.Core 版本是 3.3.3
CaSTLe.Windsor 版本是 .NET 4.5 的 3.3.0

注册代码如下:
container.Register(
Classes.FromThisAssembly()
.Where(type => type.Name.EndsWith("Service"))
.WithServiceDefaultInterfaces()
.Configure(c => c.LifestyleTransient()));

非常感谢。

最佳答案

你没有展示你是如何注册你的接口(interface)和类的,但很可能你正在使用 DefaultInterfaces 惯例。

This method performs matching based on type name and interface's name. Often you'll find that you have interface/implementation pairs like this: ICustomerRepository/CustomerRepository, IMessageSender/SmsMessageSender, INotificationService/DefaultNotificationService. This is scenario where you might want to use DefaultInterfaces method to match your services. It will look at all the interfaces implemented by selected types, and use as type's services these that have matching names. Matching names, means that the implementing class contains in its name the name of the interface (without the I on the front).



有许多不同的约定,但您可能只是在寻找 AllInterfaces :

When a component implements multiple interfaces and you want to use it as a service for all of them, use WithService.AllInterfaces() method.

关于c# - CaSTLe.Windsor - 为什么名称需要与界面相似?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42117638/

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