WCF with ninject example

First of all, I have never seen an example of using ninject with wcf.

This is my .svc:

<%@ ServiceHost Language="C#" Debug="true" Service="MyService.Services.NotifyService" %>

My service:

[ServiceContract]
public interface INotifyService
{
    [OperationContract]
    void SendEmail(string to, string from, string message);
}

class NotifyService : INotifyService
{
    private IEmailRepository emailRepo;

    public NotifyService(IEmailRepository emailRepo)
    {
        if (emailRepo== null) throw new ArgumentNullException("emailRepo");
        this.emailRepo= emailRepo;
    }
    public void SendEmail(string to, string from, string message)
    {
        //do stuff here
    }
}

Using this information, how can I add an injection MyEmailRepositoryto NotifyService?

If I do not have a default constructor, wcf throws an error with the request. I also have experience using ninject with asp.net mvc3 if that helps.

+5
source share
3 answers

Use custom IInstanceProviderto resolve your service instance. Here is an example:

http://orand.blogspot.com/2006/10/wcf-service-dependency-injection.html

+5

This answer in SO provides a complete implementation to add NInject to a WCF project.

I will not copy and paste it here, but basically after installing the extensions Ninject, Ninject.Extensions.Wcfand Ninject.Web.Commonthrough Nuget you will need to create three classes:

public class NInjectInstanceProvider : IInstanceProvider, IContractBehavior
public class NInjectServiceHostFactory : ServiceHostFactory
public class NInjectServiceHost : ServiceHost

Then specify the attribute Factoryin your .svc (right-click the file in Solution Explorer, then select "View Markup") in the class NInjectServiceHost:

<%@ ServiceHost ... Factory="SomeNamespace.NInjectServiceHostFactory" %>
0
source

All Articles