Ninject's AllowNullInjection not working in ASP.NET WCF

145 Views Asked by At

I am using the following Ninject's NuGet packages in my ASP.NET WCF Project:

  • Ninject
  • Ninject.Web.Common
  • Ninject.Web.Common.WebHost
  • Ninject.Extensions.Wcf

My WCF Service FooService depends on IRepository which has a concrete implementation FooRepository like this:

[ServiceContract]
public interface IFooService
{
    [OperationContract]
    IEnumerable<Foo> GetFoos();
}

public class FooService : IFooService
{
    private readonly IRepository _repository;

    public FooService(IRepository repository)
    {
        _repository = repository;
    }
}

public class FooRepository : IRepository
{
    private readonly FooContext _fooContext;
    private readonly ILogger _logger;

    public FooRepository(FooContext fooContext, ILogger logger)
    {
        _fooContext = fooContext;
        _logger = logger;
    }
}

FooService.svc:

<%@ ServiceHost Language="C#" 
                Debug="true" 
                Service="FooNamespace.FooService" 
                CodeBehind="FooService.svc.cs" 
                Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory" %>

And I set up my dependencies in NinjectWebCommon.cs like this:

private static void RegisterServices(IKernel kernel)
{
    kernel.Settings.AllowNullInjection = true;
    kernel.Bind<IRepository>().To<FooRepository>().InRequestScope();

    // I want to bind null to ILogger through the Settings property
    // instead of manually calling Bind<ILogger>().ToConstant<ILogger>(null)
}       

But I still got an ActivationException when my WCF service is activated:

Error activating ILogger
No matching bindings are available, and the type is not self-bindable.
Activation path:
 2) Injection of dependency ILogger into parameter logger of constructor of type FooRepository
 1) Injection of dependency IRepository into parameter repository of constructor of type FooService

How can I set up optional injection in this case?

0

There are 0 best solutions below