Click here to Skip to main content
13,045,566 members (68,389 online)
Click here to Skip to main content
Add your own
alternative version

Stats

32.7K views
485 downloads
15 bookmarked
Posted 5 Jan 2012

ASP.NET Web Services Dependency Injection using Unity

, 14 Feb 2017
Rate this:
Please Sign up or sign in to vote.
Web Services Dependency Injection using Unity

In this article I'll show you how to setup Unity IoC container in an existing ASP.NET 3.5 Web Forms application and use it in your Web Services (.asmx files).

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)
Italy Italy
My name is Rui Jarimba and I was born in Madeira island, Portugal and I currently live in Rome, Italy.

I have more than 10 years of experience developing software using the .NET Framework and other technologies (Web development, Databases, ...).

Some of my professional interests are: software development best practices, software architecture, cloud computing, Continuous Integration (CI), Continuous Delivery (CD) and agile methodologies such as Scrum, Kanban, Lean and any other methodology that can help me to become a better and more productive software engineer.

I believe in good code - code that is readable, maintainable, reusable, testable and deployable. This means that I'm not the "quick and dirty" type, I write code for the medium/long term whenever possible.

Something else about me - I love music, I am an amateur photographer, not a big fan of gyms (I prefer to do some outdoor activity such as walking/hiking), big foodie (I love Mediterranean cuisine and my glass of wine!).

You may also be interested in...

Pro

Comments and Discussions

 
QuestionASP.NET Web Services Dependency Injection using Unity Pin
Member 364734516-Apr-12 3:09
memberMember 364734516-Apr-12 3:09 
AnswerRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba16-Apr-12 3:17
memberRui Jarimba16-Apr-12 3:17 
AnswerRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba16-Apr-12 3:19
memberRui Jarimba16-Apr-12 3:19 
AnswerRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba16-Apr-12 4:44
memberRui Jarimba16-Apr-12 4:44 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Member 364734517-Apr-12 22:57
memberMember 364734517-Apr-12 22:57 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba17-Apr-12 23:01
memberRui Jarimba17-Apr-12 23:01 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba18-Apr-12 0:06
memberRui Jarimba18-Apr-12 0:06 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Member 364734522-Apr-12 22:21
memberMember 364734522-Apr-12 22:21 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba22-Apr-12 22:56
memberRui Jarimba22-Apr-12 22:56 
Oi,

As propriedades não podem ser privadas.Na secção "References" tem um link para um artigo que mostra como usar Unity com páginas ASP.NET Webforms.

Cumprimentos,
Rui
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Member 364734524-Apr-12 1:40
memberMember 364734524-Apr-12 1:40 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Member 364734524-Apr-12 22:07
memberMember 364734524-Apr-12 22:07 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba2-May-12 6:24
memberRui Jarimba2-May-12 6:24 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Member 36473453-May-12 0:15
memberMember 36473453-May-12 0:15 

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

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 15 Feb 2017
Article Copyright 2012 by Rui Jarimba
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid