Dependency injection in WCF service using AutoFac

Dependency injection is one form of the broader technique of inversion of control (SOLID – Dependency inversion principles). In software, There should be less coupling between component and cohesion should be high. High level module should not depend on low level modules rather should depend on Abstraction.

Many times we need to inject dependencies in WCF service. In this blog, we will just focus on how to inject dependencies using Autofac.

What is Autofac?

Autofac is an addictive IoC container for Microsoft .NET 4.5, Silverlight 5, Windows Store apps, and Windows Phone 8 apps. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity. This is achieved by treating regular .NET classes as components. You can learn more about AutoFac from here.

You need to follow below steps to inject dependencies using Autofac in WCF service. Lets get started with the example:

Step 1:

Lets create WCF service application

1. Create projects
Creation of WCF service

Step 2:

We need to install below nuget packages in service.

  1. Autofac
  2. Autofac.Wcf
2. nuget packages
Nuget packages

Step 3:

Lets create one sample repository and its implementation.

4. IMyrepository
Interface
3. Repository implementation
Implementation of Interface

Step 4:

You need to open markup file of service and need to add below code in svc file.

Just right click on “Service1.svc” and then click on “View markup”  from solution explorer.

7. Markup setting
Service markup file

You need to add Factory tag as it is. There will be change in Service part. Please follow below format

“<namespace of interface>.<Interface name>, Assembly name”,

so in above example MyService is namespace of interface, IService1 is interface and lastpart Myservice is an assembly name.

Step 5:

You need to register all your dependencies to the container. Below I have used “Instance per dependency” scope it means a unique instance will be returned from each request for a service. You can learn more about instance scope from here

Binder class - register depedencies
Register dependencies

After registering these dependencies, you need to assign above returned container to AutofacHostFactory.Container in the start method of Global.asax.

Application start method
Application startup

That’s it.  See output below

Output
Test

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *