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.
See https://github.com/ninject/ninject.extensions.wcf/tree/master/src/Examples/WcfTimeService
Use a custom IInstanceProvider
to resolve your service instance. Here is an example:
http://orand.blogspot.com/2006/10/wcf-service-dependency-injection.html
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" %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With