Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET

ASP.NET Web Services Dependency Injection using Unity

Rate me:
Please Sign up or sign in to vote.
4.90/5 (7 votes)
14 Feb 2017CPOL1 min read 57.3K   815   16   14
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:

C#
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.

C#
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).

C#
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.

C#
[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. :)

Image 2

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)


Written By
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!).

Comments and Discussions

 
PraiseGreat work thank you! Pin
Member 1417927312-Mar-19 0:05
Member 1417927312-Mar-19 0:05 
QuestionASP.NET Web Services Dependency Injection using Unity Pin
Member 364734516-Apr-12 3:09
Member 364734516-Apr-12 3:09 
AnswerRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba16-Apr-12 3:17
professionalRui Jarimba16-Apr-12 3:17 
AnswerRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba16-Apr-12 3:19
professionalRui Jarimba16-Apr-12 3:19 
AnswerRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba16-Apr-12 4:44
professionalRui Jarimba16-Apr-12 4:44 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Member 364734517-Apr-12 22:57
Member 364734517-Apr-12 22:57 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba17-Apr-12 23:01
professionalRui Jarimba17-Apr-12 23:01 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba18-Apr-12 0:06
professionalRui Jarimba18-Apr-12 0:06 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Member 364734522-Apr-12 22:21
Member 364734522-Apr-12 22:21 
Oi Rui,

Percebi q voce fala portugues Smile | :)

Espero q tudo esteja bem com vc.

The LogWriter class eh parte da Microsoft Enterprise Library e eu acho q nao ha uma interface pra usar. Mas eu tambem tentei usar com uma class e interface q eu criei mas ainda voltou como null.

Eu acho q o problema eh q eu estou tentando usar o seu codigo com uma pagina aspx.

public partial class LabellerNoService : BasePage<LabellerNoService>//System.Web.UI.Page
{
........


[Dependency]
private LogWriter Logger { set; get; }


}

Eh possivel user com paginas tambem ou so web services?

Cheers

C
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba22-Apr-12 22:56
professionalRui Jarimba22-Apr-12 22:56 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Member 364734524-Apr-12 1:40
Member 364734524-Apr-12 1:40 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Member 364734524-Apr-12 22:07
Member 364734524-Apr-12 22:07 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Rui Jarimba2-May-12 6:24
professionalRui Jarimba2-May-12 6:24 
GeneralRe: ASP.NET Web Services Dependency Injection using Unity Pin
Member 36473453-May-12 0:15
Member 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.