1

I am using Unity in an ASP.NET project (not MVC). It seems that the Unit Tests need to be aware of Unity, create an IoC container and insert Mocks into that, unlike the other unit testing frameworks I have used.

The examples of resolving classes using Unity seems to be either:

public class Foo
{

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

}

or resolving directly from the container:

UnityTest.Interfaces.IMenuBL ser = Global.Container.Resolve<UnityTest.Interfaces.IMenuBL>(); 

Is it possible, in non-MVC ASP.NET to have Unity perform constructor injection so that my unit tests aren't tied to my IoC container?

Cheers

Dave

BanksySan
  • 27,362
  • 33
  • 117
  • 216
  • 1
    If you're using Web Forms you can do property injection. David Hayden had a screencast showing how to do it, but I cannot find it anymore. I wrote an article on how to do it using ASP.NET Web Services, it should be easy enough for you to adapt it and use it with Web Forms: http://ruijarimba.wordpress.com/2011/12/27/asp-net-web-services-dependency-injection-using-unity/ – Rui Jarimba Oct 29 '13 at 14:03
  • Thanks Rui, I don't think this is a Unity scecific thing. Are any IoC containers able to provide constructor injection on WebForms? – BanksySan Oct 29 '13 at 14:24
  • No, it's not an Unity specific thing, I think you'll have the same problem with other IoC containers. I know that property injection is not ideal, but that's what you have to do with ASP.NET Web Forms.... :( – Rui Jarimba Oct 29 '13 at 14:27
  • 1
    @RuiJarimba, if you want to add "You can't perform constructor injection with any current IoC frameworks and WedForms" as an answer below then I'll mark it as correct. – BanksySan Oct 29 '13 at 14:44

1 Answers1

2

ASP.NET Web Forms weren't designed with testability in mind. You can't do constructor injection with Web Forms, at least not without using some dodgy workarounds like creating a page handler - see How to use Dependency Injection with ASP.NET Web Forms.

The best option is to use property injection.

Edit: you may consider using the MVP pattern in order to improve the testability of your Web Forms pages:

MSDN - Better Web Forms with the MVP Pattern

Community
  • 1
  • 1
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
  • 1
    Good addition of the MVP pattern! I was just thinking that the code pages are going to have to be thin as hair. – BanksySan Oct 29 '13 at 15:11