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