我正在尝试使用 WCF Ninject 扩展将 Ninject 添加到 WCF 服务。
我收到错误:
提供的服务类型无法作为服务加载,因为它没有默认(无参数)构造函数。要解决此问题,请将默认构造函数添加到类型,或将类型的实例传递给主机。
该服务具有 Ninject 服务主机工厂:
<%@ ServiceHost Language="C#" Debug="true" CodeBehind="SchedulingSvc.svc.cs"
Service="Scheduling.SchedulingSvc"
Factory="Ninject.Extensions.Wcf.NinjectWebServiceHostFactory" %>
global.asax 文件继承自 NinjectHttpApplication 并且 CreateKernel 返回一个带有 NinjectModule 的新内核:
public class Global : NinjectHttpApplication
{
protected override IKernel CreateKernel()
{
return new StandardKernel(new NinjectServiceModule());
}
}
忍者模块:
public class NinjectServiceModule : NinjectModule
{
public override void Load()
{
this.Bind<ISchedulingService>().To<SchedulingSvc>();
this.Bind<ISchedulingBusiness>().To<SchedulingBusiness>();
}
}
带有构造函数注入的服务:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SchedulingSvc : ISchedulingService
{
private ISchedulingBusiness _SchedulingBusiness = null;
public SchedulingSvc(ISchedulingBusiness business)
{
_SchedulingBusiness = business;
}
public CalendarEvent[] GetCalendarEvents()
{
var calendarEvents = _SchedulingBusiness.GetCalendarEvents();
return calendarEvents;
}
...
}
具有属性注入的服务:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SchedulingSvc : ISchedulingService
{
[Inject] public ISchedulingBusiness _SchedulingBusiness { get; set; }
public SchedulingSvc()
{
}
public CalendarEvent[] GetCalendarEvents()
{
var calendarEvents = _SchedulingBusiness.GetCalendarEvents();
return calendarEvents;
}
...
}
如果我使用构造函数注入,我会得到帖子顶部提到的错误。如果我尝试使用属性注入,则 _ScheduleBusiness 始终为空。
我错过了什么?