c# – WCF / Ninject / Default(无参数)构造函数

我正在尝试使用WCF Ninject扩展将Ninject添加到WCF服务.

我收到错误:

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.

该服务有Ninject Service Host工厂:

<%@ 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());
    }
}

NinjectModule:

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始终为null.

我错过了什么?

最佳答案 我遇到该错误消息的唯一一次是在尝试使用拦截器时(通过使用Ninject.Extensions.Interceptor库和/或Castle DynamicProxy.)这是不喜欢带参数的构造函数的部分.

否则,这应该工作正常.你似乎没有使用任何拦截器,所以我可以问这个目的是什么?:

this.Bind<ServiceHost>().To<NinjectServiceHost>();

我假设你在这里使用某种自定义服务主机,但它不应该是你想要做的事情.使您的上述代码工作所需的只是:

1:服务标记中的Factory属性(你有这个)
2:内核中的构造函数依赖项绑定(你有这个)

我现在有这个确切的设置工作,所以我认为你的NinjectServiceHost中的某些东西导致了这个问题并试图附加某种类型的拦截器.

点赞