c# - WCF/Ninject/默认(无参数)构造函数

标签 c# wcf ninject ninject-extensions

我正在尝试使用 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 服务主机工厂:

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

带有构造函数注入(inject)的服务:

[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;
    }
    ...
}

带有属性注入(inject)的服务:

[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;
    }
    ...
}

如果我使用构造函数注入(inject),我会收到帖子顶部提到的错误。如果我尝试使用属性注入(inject),_ScheduleBusiness 始终为空。

我错过了什么?

最佳答案

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

否则,这应该可以正常工作。看起来你没有使用任何拦截器,请问这样做的目的是什么?:

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

我假设您在这里使用了某种自定义服务主机,但对于您尝试执行的操作而言,这不是必需的。使上述代码正常工作所需要做的就是:

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

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

关于c# - WCF/Ninject/默认(无参数)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17193562/

相关文章:

c# - 如何在 ASP.NET 上发生断开连接时立即检测到而不进行轮询?

c# - 找不到 WS-Security header

c# - Ninject 工厂扩展和 InCallScope 没有给出预期的结果

asp.net - 设计一个可单元测试的类

c# - .NET 中 RSA key 指数有限制吗?

c# - Windows 和 Linux 应用程序之间的管道

c# - 无法让 EF Code First 在 MVC 4 中工作

c# - 在 C# 中调试 Windows 服务调用的 WCF 服务

c# - 需要保护 WCF 数据,但只是一个部分

ninject - 有人使用 Ninject 2.0 作为 nServiceBus ObjectBuilder 吗?