C# WCF - Ninject Ioc

1 minute read

In order to use Ioc to instantiate a WCF service class, Ioc should provide implementation of following two interfaces.
IInstanceProvider
IServiceBehavior

Implement IServiceBehavior

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    public class NinjectBehaviorAttribute : Attribute, IServiceBehavior
    {
        public void AddBindingParameters(ServiceDescription serviceDescription,
            ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints,
            BindingParameterCollection bindingParameters)
        {
        }
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            Type serviceType = serviceDescription.ServiceType;
            IInstanceProvider instanceProvider = new NinjectInstanceProvider(NinjectServiceLocator.Kernel, serviceType);
            foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
            {
                foreach (EndpointDispatcher endpointDispatcher in dispatcher.Endpoints)
                {
                    DispatchRuntime dispatchRuntime = endpointDispatcher.DispatchRuntime;
                    dispatchRuntime.InstanceProvider = instanceProvider;
                }
            }
        }
        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
        }
    }

Implement IInstanceProvider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    public class NinjectInstanceProvider : IInstanceProvider
    {
        private Type serviceType;
        private IKernel kernel;
        public NinjectInstanceProvider(IKernel kernel, Type serviceType)
        {
            this.kernel = kernel;
            this.serviceType = serviceType;
        }
        public object GetInstance(InstanceContext instanceContext)
        {
            return this.GetInstance(instanceContext, null);
        }
        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            return kernel.Get(this.serviceType);
        }
        public void ReleaseInstance(InstanceContext instanceContext, object instance)
        {
        }
    }

Example class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[ServiceContract]
public interface IExample
{
    void Test();
}
[NinjectBehavior]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public Example : IExample
{
    ITest _testIntf;
    IMathTest _mathTestIntf;
    public Example(ITest testIntf, IMathTest mathTestIntf)
    {
        _testIntf = testIntf;
        _mathTestIntf = mathTestIntf;
    }
    public void Test()
    {
    }
}