Click here to Skip to main content
Click here to Skip to main content
Technical Blog

ASP.NET Web Services Dependency Injection using Unity

, 16 Apr 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Web Services Dependency Injection using Unity

Recently, I had to setup Unity IoC container in an existing ASP.NET 3.5 Web Forms application. This application had not only web pages (.aspx files), but also some Web Services (.asmx files). After some research, I found out David Hayden’s screencast: Unity IoC and ASP.NET screencast – Dependency Injection into Web Pages.

You can use a similar technique for your Web Services – that’s what I’ll show you in this article.

Table of contents

Example – Adding logging to your application

You have the following interface and its implementation:

public interface ILogger
{
    void Write(string message);
}

public class DebugLogger : ILogger
{
    public void Write(string message)
    {
        Debug.WriteLine(message);
    }
}

Step 1: Setting up the container in Global.asax

The first step is to setup Unity Container in Global.asax file. This is a good place to do it because it can be accessed either by web pages or by Web Services. The CreateContainer() method is the place where the dependencies are specified.

public class Global : HttpApplication, IContainerAccessor
{
    private static IUnityContainer _container;

    public static IUnityContainer Container
    {
        get
        {
            return _container;
        }
        private set
        {
            _container = value;
        }
    }

    IUnityContainer IContainerAccessor.Container
    {
        get
        {
            return Container;
        }
    }

    protected void Application_Start(object sender, EventArgs e)
    {
        CreateContainer();
    }

    protected virtual void CreateContainer()
    {
        IUnityContainer container = new UnityContainer();
        container.RegisterType<ILogger, DebugLogger>();
        
        Container = container;
    }
}

Step 2: Creating a base class for the services

Create a generic BaseService that all your services will inherit from. The dependencies will be injected when you create an instance of the service (default constructor).

public abstract class BaseService<T> : System.Web.Services.WebService where T : class
{
    public BaseService()
    {
        InjectDependencies();
    }

    protected virtual void InjectDependencies()
    {
        HttpContext context = HttpContext.Current;

        if (context == null)
            return;

        IContainerAccessor accessor = context.ApplicationInstance as IContainerAccessor;

        if (accessor == null)
            return;

        IUnityContainer container = accessor.Container;

        if (container == null)
            throw new InvalidOperationException(
              "Container on Global Application Class " + 
              "is Null. Cannot perform BuildUp.");

        container.BuildUp(this as T);
    }
}

Step 3: Setting up the services

Now all you need to do is to inherit from the BaseService and invoke its base constructor. Don’t forget to add the [Dependency] attribute to your dependency, and it has to be public.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class DummyService : BaseService<DummyService>
{
    [Dependency]
    public ILogger Logger
    {
        get;
        set;
    }

    public DummyService() : base()
    {
    }

    [WebMethod]
    public string HelloWorld(string name)
    {
        string message = string.Format("Hello World, {0}!", name);

        this.Logger.Write(message);

        return message;
    }
}

That’s it! Now you just need to compile and run the application and see it in action :)

Feel free to download the demo application.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Rui Jarimba
Software Developer (Senior)
Ireland Ireland
My name is Rui Jarimba and I was born in Madeira island, Portugal and I currently live in Dublin, Ireland.
 
I’m working as a .NET software developer since 2005.
 
Some of my professional interests are:
 
Web development using .NET Framework;
Service Oriented Architecture (SOA);
Database development and modelling;
Web accessibility, usability, and standards;
Software Architecture;
Design Patterns
Follow on   Twitter   LinkedIn

Comments and Discussions

 
QuestionASP.NET Web Services Dependency Injection using Unity PinmemberMember 364734516-Apr-12 4:09 
AnswerRe: ASP.NET Web Services Dependency Injection using Unity PinmemberRui Jarimba16-Apr-12 4:17 
AnswerRe: ASP.NET Web Services Dependency Injection using Unity PinmemberRui Jarimba16-Apr-12 4:19 
AnswerRe: ASP.NET Web Services Dependency Injection using Unity PinmemberRui Jarimba16-Apr-12 5:44 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity PinmemberMember 364734517-Apr-12 23:57 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity PinmemberRui Jarimba18-Apr-12 0:01 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity PinmemberRui Jarimba18-Apr-12 1:06 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity PinmemberMember 364734522-Apr-12 23:21 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity PinmemberRui Jarimba22-Apr-12 23:56 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity PinmemberMember 364734524-Apr-12 2:40 
Oi Rui,
 
O autor removeu o conteudo do link na seccao "References".
 
Infelizmente esse artigo sumiu...
 
Cheers
 
C
 
<a href="http://www.pnpguidance.net/Post/UnityIoCASPNETScreencastDependencyInjectionWebPages.aspx">http://www.pnpguidance.net/Post/UnityIoCASPNETScreencastDependencyInjectionWebPages.aspx</a>[<a href="http://www.pnpguidance.net/Post/UnityIoCASPNETScreencastDependencyInjectionWebPages.aspx" target="_blank" title="New Window">^</a>]
GeneralRe: ASP.NET Web Services Dependency Injection using Unity PinmemberMember 364734524-Apr-12 23:07 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity PinmemberRui Jarimba2-May-12 7:24 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity PinmemberMember 36473453-May-12 1:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 16 Apr 2012
Article Copyright 2012 by Rui Jarimba
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid