ASP.NET 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

Downloads

Download the demo project (VS2010): UnityAsmxWebServices.zip

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s