Implementing Unity with IoC in ASP.Net

Jun 16, 2008 at 10:20 AM


1. ObjectBuilder
Using existing ObjectBuilder, I am able to do DI through external mapping (example below):

protected virtual void AddGlobalServices(IServiceCollection globalServices)
            globalServices.AddNew<Logger, ILogger>();

public AssetHierarchyController([ServiceDependency] ILogger logger)

The DI above will work and ILogger will resolve to Logger class correctly.

2. Spring.Net
Next, I evaluate Excellently, I am able to map through xml configuration file, and the DI will know how to resolve automatically.

3. Unity (Example 1)
Then, I want to do the same for Unity. I read the thread and the uploaded example of DI for ASP.Net (by alexanderQX) for Unity is below:

protected void Page_Load(object sender, EventArgs e)
    IUnity UnityCtx = Context.ApplicationInstance as IUnity;
    // This should find the WebLogger when trying resolve the ILogger
    ILogger logger = UnityCtx.Container.Resolve<ILogger>();

The above is not good as it needs additional line to bind the Unity container. I tried to modify his sample and do property injection of ILogger (see below):

private ILogger _logger;

public ILogger Logger
    get { return _logger; }
    set { _logger = value; }

It never works and _logger is always null.

4. Unity (Example 2)
I then study David Hayden's Unity IoC tutorial. If you read his screencast and from extract below:

public BlogDataSource(ILogger logger)

It is very clear that his example of Unity of DI is good and ILogger is able to resolve correctly, without additional binding of Unity container in the class. 

However, I am unable to get his tutorial working in my project due to many missing pieces.

So trying to ask for help here. Has anyone able to get Unity working with IoC in class without the hassle of declare and bind Unity container first? It can be through constructor or property injection..



Jun 18, 2008 at 3:51 PM

Check out my screencast and download the example code from  it and let me know if it solves your problem.

Unity IoC and ASP.NET Screencast - Dependency Injection into Web Pages

Best Regards,


David Hayden
Microsoft MVP C#