Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF with ninject example

Tags:

wcf

ninject

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 do I dependency inject MyEmailRepository in NotifyService?

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

like image 563
Shawn Mclean Avatar asked Jul 12 '11 19:07

Shawn Mclean


3 Answers

See https://github.com/ninject/ninject.extensions.wcf/tree/master/src/Examples/WcfTimeService

like image 70
Remo Gloor Avatar answered Sep 30 '22 18:09

Remo Gloor


Use a custom IInstanceProvider to resolve your service instance. Here is an example:

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

like image 37
Jeff Avatar answered Sep 30 '22 18:09

Jeff


This answer at SO provides a full implementation to add NInject to a WCF project.

I won't copy and paste it here, but basically, after installing the Ninject, Ninject.Extensions.Wcf and Ninject.Web.Common extensions through Nuget, you'll have to create three classes:

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

Then point the Factory attribute in your .svc (right click the file on Solution Explorer, then choose "View Markup") to the NInjectServiceHost class:

<%@ ServiceHost ... Factory="SomeNamespace.NInjectServiceHostFactory" %>
like image 29
Marcos Dimitrio Avatar answered Sep 30 '22 18:09

Marcos Dimitrio