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

4
  • 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: ruijarimba.wordpress.com/2011/12/27/… Commented Oct 29, 2013 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? Commented Oct 29, 2013 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.... :( Commented Oct 29, 2013 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. Commented Oct 29, 2013 at 14:44

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Good addition of the MVP pattern! I was just thinking that the code pages are going to have to be thin as hair.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.