I'm trying to add Ninject to a WCF service using the WCF Ninject extension.
I'm getting the error:
The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
The service has the Ninject Service Host factory:
<%@ ServiceHost Language="C#" Debug="true" CodeBehind="SchedulingSvc.svc.cs"
Service="Scheduling.SchedulingSvc"
Factory="Ninject.Extensions.Wcf.NinjectWebServiceHostFactory" %>
The global.asax file inherits from NinjectHttpApplication and CreateKernel returns a new Kernel with A NinjectModule:
public class Global : NinjectHttpApplication
{
protected override IKernel CreateKernel()
{
return new StandardKernel(new NinjectServiceModule());
}
}
The NinjectModule:
public class NinjectServiceModule : NinjectModule
{
public override void Load()
{
this.Bind<ISchedulingService>().To<SchedulingSvc>();
this.Bind<ISchedulingBusiness>().To<SchedulingBusiness>();
}
}
The service with constructor injection:
[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;
}
...
}
The service with property injection:
[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;
}
...
}
If I use constructor inject, I get the error mentioned at the top of the post. If I try to use property injection, the _ScheduleBusiness is always null.
What am I missing?
The only time I encounter that error message is when attempting to use an Interceptor (through using the Ninject.Extensions.Interceptor library and/or Castle DynamicProxy.) That is the part that doesn't like constructors with parameters.
Otherwise, this should be working fine. It doesn't seem like you're using any Interceptors, so may I ask what is the purpose of this?:
this.Bind<ServiceHost>().To<NinjectServiceHost>();
I assume you're using some kind of custom service host here, but it shouldn't be necessary for what you're trying to do. All you need to get your above code working is:
1: The Factory attribute in the service markup (you have this) 2: The constructor dependency bound in your kernel (you have this)
I have this exact setup working right now, so I think something in your NinjectServiceHost is causing this problem and attempting to attach an interceptor of some sort.