在BasePage.cs类中,我有以下IIndex属性,它应该有两个或更多的INotificationService实现,这些实现可以使用密钥访问。
public class BasePage : Page
{
public IIndex<string, INotificationService<INotification>> NotificationServices { get; set; }
public INotificationService<INotification> EmailService
{
get
{
return NotificationServices["emailService"];
}
}
public INotificationService<INotification> FaxService
{
get
{
return NotificationServices["faxService"];
}
}
}具体课程:
public class FaxNotificationService : INotificationService<FaxNotification>
{
private IClient _smtpClient;
public FaxNotificationService(IClient smtpClient)
{
_smtpClient = smtpClient;
}
public void Send(FaxNotification notification)
{
_smtpClient.Send(notification);
}
}
public class EmailNotificationService : INotificationService<EmailNotification>
{
private IClient _smtpClient;
public EmailNotificationService(IClient smtpClient)
{
_smtpClient = smtpClient;
}
public void Send(EmailNotification notification)
{
_smtpClient.Send(notification);
}
}在Global.asax.cs中
void Application_Start(object sender, EventArgs e)
{
var emailSmtp = new SmtpWrapper(new SmtpClient
{
...
});
var faxSmtp = new SmtpWrapper(new SmtpClient
{
...
});
var builder = new ContainerBuilder();
// before having the generic interface the following commented code worked perfectly fine
//builder.RegisterType<EmailNotificationService>()
// .Named<INotificationService>("emailService")
// .WithParameter("smtpClient", emailSmtp);
//builder.RegisterType<FaxNotificationService>()
// .Named<INotificationService>("faxService")
// .WithParameter("smtpClient", faxSmtp);
builder.RegisterType<EmailNotificationService>()
.Named<INotificationService<INotification>>("emailService")
.WithParameter("smtpClient", emailSmtp);
builder.RegisterType<BasePage>().AsSelf();
var build = builder.Build();
_containerProvider = new ContainerProvider(build);
using (var scope = build.BeginLifetimeScope())
{
var service = scope.Resolve<BasePage>();
}
}在Global.asax.cs中,我试图以同样的方式注册EmailNotificationService,但我得到了一个例外:
类型'NotificationServices.EmailNotificationService‘不能分配给服务'emailService (Shared.NotificationServices.Abstractions.INotificationService`1[Shared.NotificationServices.Abstractions.INotification .
,现在我知道为什么它不起作用了。因为在C#中,甚至不可能执行以下操作:
INotificationService<INotification> service = new EmailNotificationService(new SmtpWrapper(new SmtpClient())); 后面的代码行将导致编译时错误:
不能隐式地将类型'NotificationServices.EmailNotificationService‘转换为'Shared.NotificationServices.Abstractions.INotificationService'.存在显式转换(是否缺少强制转换?)
因此,任何想法的人:)
发布于 2019-06-14 15:28:28
它们可能实现相同的接口,但它们不一定会被同等对待。类型是一个重要的区别因素。解决这个问题是文档中的一个常见问题。
https://stackoverflow.com/questions/56583975
复制相似问题