Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

WCF Service and Ninject

4.71/5 (5 votes)
9 May 2016CPOL1 min read 19.1K   1  
Dependecy injection with ninja

Introduction

Recently, I was looking for a way in which to use Dependency Injection Container in WCF service.

For my MVC projects, I usually use Unity, but I wasn’t able to make it work for WCF service, so I was looking for an alternative and I found it is very easy to use Ninject.

This article should illustrate how to setup WCF service and make it work with Ninject DIC.

WCF Service

Start by creating the WCF service.

create service

Setup Ninject

Next step is to install Ninject NuGet packages:

Capture2

ninject ninject-webhost

At this point, the structure of your project should look like this:

ninjectwebcommon

IDataReader is my custom object that I call from Service1 and it is actually the interface that we need to inject into Service1 constructor. DataReader is implementation of this interface.

Service1

C#
//interface
[ServiceContract]
public interface IService1
{
    [OperationContract]
    string GetData(int value);
}

//service
public class Service1 : IService1
{
    IDataReader _reader;
    public Service1(IDataReader reader)
    {
        _reader = reader;
    }

    public string GetData(int value)
    {
        return _reader.ReadData(value);
    }
}

IDataReader and DataReader

C#
//interface
public interface IDataReader
{
    string ReadData(int value);
}

//class
public class DataReader : IDataReader
{

    public string ReadData(int value)
    {
        return string.Format("Data for value: {0} is {1}", value, new Guid());
    }
}

In order to inject the interface into constructor, you need to register it in Ninject container like this:

C#
private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IDataReader>().To<DataReader>();
}

Now, if you would run the application, you would get this error:

error

The problem is that you’ve just set up the container, but you didn’t wire it into the application.

Wire the Ninject into the Application

You need to change the Service settings.

You can do this by markup:

viewmarkup

and you need to change the code accordingly:

C#
//original
<%@ ServiceHost Language="C#" Debug="true" 
Service="WcfDemo.Service1" CodeBehind="Service1.svc.cs" %>

//with ninject factory
<%@ ServiceHost Language="C#" 
Debug="true" Service="WcfDemo.Service1" 
CodeBehind="Service1.svc.cs" 
Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory" %>

Summary

I think it is very easy to set up Ninject DIC into WCF service and it can bring you a lot of benefits to have DIC in your application.

You can download the entire working project here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)