在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'。存在显式转换(您是否缺少演员表?)
所以任何有想法的人:)